import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from threading import Thread
from urllib.parse import parse_qs, urlparse

import typer

from . import config as cfg_module

AUTH_URL = "https://sixtysix.pro/auth/cli?port=54321"
CALLBACK_PORT = 54321


def login() -> None:
    """Authenticate with your SixtySix account."""
    result: dict = {}

    class CallbackHandler(BaseHTTPRequestHandler):
        def log_message(self, *args):  # type: ignore[override]
            pass

        def do_GET(self) -> None:
            parsed = urlparse(self.path)
            if parsed.path != "/callback":
                self.send_response(404)
                self.end_headers()
                return

            params = parse_qs(parsed.query)
            refresh_token = params.get("refresh_token", [""])[0]
            email = params.get("email", [""])[0]
            error = params.get("error", [""])[0]

            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()

            if not refresh_token:
                err_msg = error or "no token received"
                self.wfile.write(
                    f"""<html><body style="font-family:system-ui;display:flex;justify-content:center;padding:4rem">
<div><h2>Authentication failed</h2><p>{err_msg}</p>
<p style="color:#888">You can close this window.</p></div></body></html>""".encode()
                )
                result["error"] = err_msg
            else:
                self.wfile.write(
                    b"""<html><body style="font-family:system-ui;display:flex;justify-content:center;padding:4rem">
<div><h2>&#10003; Authentication successful</h2>
<p style="color:#888">You can close this window and return to the terminal.</p></div></body></html>"""
                )
                result["refresh_token"] = refresh_token
                result["email"] = email

            Thread(target=server.shutdown, daemon=True).start()

    server = HTTPServer(("127.0.0.1", CALLBACK_PORT), CallbackHandler)

    typer.echo(typer.style("Opening browser to sign in...", fg=typer.colors.CYAN))
    typer.echo()

    try:
        webbrowser.open(AUTH_URL)
    except Exception:
        typer.echo("Could not open browser automatically.")
        typer.echo("Please open this URL:")
        typer.echo()
        typer.echo(AUTH_URL)
        typer.echo()

    typer.echo("Waiting for authentication...")
    server.serve_forever()

    if "error" in result:
        typer.echo(
            typer.style(f"Authentication failed: {result['error']}", fg=typer.colors.RED),
            err=True,
        )
        raise typer.Exit(1)

    cfg = cfg_module.load()
    cfg.refresh_token = result["refresh_token"]
    cfg.user_email = result.get("email", "")
    cfg_module.save(cfg)

    # Write the token directly into the data volume so the backend reads it
    # immediately on next start — no env var handoff needed.
    token_file = cfg_module.data_dir() / ".cache" / ".refresh_token"
    try:
        token_file.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
        tmp = token_file.with_suffix(".tmp")
        tmp.write_text(result["refresh_token"])
        tmp.replace(token_file)
    except Exception as e:
        typer.echo(typer.style(f"Warning: could not write token cache: {e}", fg=typer.colors.YELLOW), err=True)

    typer.echo()
    typer.echo(typer.style("✓ Logged in successfully", fg=typer.colors.GREEN))
    if cfg.user_email:
        typer.echo(f"  Account: {cfg.user_email}")
    typer.echo()
    typer.echo("Run 'sixtysix start' to launch the backend.")
