"""Local HTTP server for OAuth callback."""

import asyncio
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs, urlparse
import threading
from typing import Any


class CallbackHandler(BaseHTTPRequestHandler):
    """HTTP handler for the callback endpoint."""

    result: dict[str, Any] | None = None
    event: threading.Event | None = None

    def log_message(self, format: str, *args) -> None:
        """Suppress log messages."""
        pass

    def do_GET(self) -> None:
        """Handle GET request to /callback."""
        parsed = urlparse(self.path)
        if parsed.path == "/callback":
            params = parse_qs(parsed.query)

            # Store result
            CallbackHandler.result = {
                "token": params.get("token", [None])[0],
                "org_id": params.get("org_id", [None])[0],
                "org_name": params.get("org_name", [None])[0],
                "email": params.get("email", [None])[0],
                "error": params.get("error", [None])[0],
            }

            # Send response
            if CallbackHandler.result.get("error"):
                html = """
                <!DOCTYPE html>
                <html>
                <head><title>Authentication Failed</title></head>
                <body style="font-family: system-ui; text-align: center; padding: 50px;">
                    <h1>Authentication Failed</h1>
                    <p>You can close this window and return to the terminal.</p>
                </body>
                </html>
                """
            else:
                html = """
                <!DOCTYPE html>
                <html>
                <head><title>Success!</title></head>
                <body style="font-family: system-ui; text-align: center; padding: 50px;">
                    <h1>Success!</h1>
                    <p>You can close this window and return to the terminal.</p>
                </body>
                </html>
                """

            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(html.encode())

            # Signal completion
            if CallbackHandler.event:
                CallbackHandler.event.set()
        else:
            self.send_response(404)
            self.end_headers()


class CallbackServer:
    """Temporary local server to receive auth callback."""

    def __init__(self, port_range: tuple[int, int] = (8400, 8450)):
        self.port_range = port_range
        self.port: int | None = None
        self.server: HTTPServer | None = None
        self._thread: threading.Thread | None = None
        self._event = threading.Event()

    def start(self) -> int:
        """Start server and return the port."""
        CallbackHandler.result = None
        CallbackHandler.event = self._event

        for port in range(self.port_range[0], self.port_range[1]):
            try:
                self.server = HTTPServer(("localhost", port), CallbackHandler)
                self.port = port

                # Run server in background thread
                self._thread = threading.Thread(target=self._serve)
                self._thread.daemon = True
                self._thread.start()

                return port
            except OSError:
                continue

        raise RuntimeError("Could not find available port")

    def _serve(self) -> None:
        """Serve requests until event is set."""
        if self.server:
            while not self._event.is_set():
                self.server.handle_request()

    def wait_for_callback(self, timeout: float = 300) -> dict[str, Any] | None:
        """Wait for callback with timeout."""
        if self._event.wait(timeout=timeout):
            return CallbackHandler.result
        return None

    def stop(self) -> None:
        """Stop the server."""
        self._event.set()
        if self.server:
            self.server.server_close()
