from http.server import BaseHTTPRequestHandler, HTTPServer
import json

HOST = "0.0.0.0"
PORT = 8899

ERROR_MESSAGE = "hour allocated quota exceeded"

class Handler(BaseHTTPRequestHandler):
    def _send(self, code: int, payload: dict):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        # Consume request body to avoid broken pipe on clients
        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            length = 0
        if length:
            _ = self.rfile.read(length)
        payload = {
            "error": {
                "message": ERROR_MESSAGE,
                "type": "quota_exceeded"
            }
        }
        self._send(429, payload)

    def log_message(self, format, *args):
        return

if __name__ == "__main__":
    server = HTTPServer((HOST, PORT), Handler)
    print(f"mock aliyun quota server running on http://{HOST}:{PORT}")
    server.serve_forever()
