#!/usr/bin/env python3
"""Minimal Cloudflare API mock for offline endpoint setup testing."""
import json
import re
import http.server
import sys

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 19999


class Handler(http.server.BaseHTTPRequestHandler):
    def _send(self, body):
        data = json.dumps(body).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if re.search(r"/dns_records", self.path):
            # No existing records — fresh create path
            self._send({"result": [], "success": True})
        else:
            # Zone lookup
            self._send({"result": [{"id": "fake-zone-id"}], "success": True})

    def do_POST(self):
        self.rfile.read(int(self.headers.get("Content-Length", 0)))
        self._send({"result": {"id": "fake-record-id", "content": "1.2.3.4"}, "success": True})

    def do_PUT(self):
        self.rfile.read(int(self.headers.get("Content-Length", 0)))
        self._send({"result": {"id": "fake-record-id", "content": "5.6.7.8"}, "success": True})

    def do_DELETE(self):
        self._send({"result": {"id": "fake-record-id"}, "success": True})

    def log_message(self, fmt, *args):
        print(f"mock-cf: {fmt % args}", flush=True)


print(f"Mock CF server listening on 127.0.0.1:{PORT}", flush=True)
http.server.HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
