"""Public site and hosted manager page routes."""

from __future__ import annotations

from functools import lru_cache
from html import escape
from pathlib import Path

from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, RedirectResponse

from hive_compute.config import get_settings
from hive_compute.coordinator.manager_auth import get_current_admin

router = APIRouter(include_in_schema=False)

SITE_ROOT = Path(__file__).resolve().parents[1] / "site"
TEMPLATE_ROOT = SITE_ROOT / "templates"
STATIC_ROOT = SITE_ROOT / "static"
APP_DOWNLOAD_DMG_ROUTE = "/download/Ambient.dmg"
APP_DOWNLOAD_ZIP_ROUTE = "/download/Ambient.app.zip"


@router.get("/", response_class=HTMLResponse)
def landing_page():
    return _load_template("landing.html")


@router.get("/download", response_class=HTMLResponse)
def download_page():
    settings = get_settings()
    app_download_route = settings.get_public_app_download_route()
    if settings.public_worker_enrollment_enabled:
        setup_step_title = "Open the app and let it connect"
        setup_step_body = (
            "On first launch Ambient registers this Mac automatically and starts in the menu bar. "
            "Private deployments can still ask for an invitation code if they keep invite-only enrollment enabled."
        )
        install_helper = (
            "Checks macOS 13+, installs Python 3.12 via Homebrew if needed, creates "
            "<code>~/.ambient/venv</code>, and self-registers this Mac. "
            "Invite-only deployments can still pass <code>HIVE_ENROLLMENT_TOKEN</code>."
        )
    else:
        setup_step_title = "Paste your invitation code on first launch"
        setup_step_body = (
            "Ambient asks for the one-time invitation code from your welcome email or manager dashboard, "
            "then joins the network. The Whisper model downloads automatically the first time your Mac receives work."
        )
        install_helper = (
            "Checks macOS 13+, installs Python 3.12 via Homebrew if needed, creates "
            "<code>~/.ambient/venv</code>, and runs invitation-code onboarding."
        )

    return HTMLResponse(
        _render_template(
            "download.html",
            APP_DOWNLOAD_URL=escape(app_download_route),
            INSTALL_COMMAND=escape(f"curl -fsSL {_public_site_origin()}/install.sh | sh"),
            SETUP_STEP_TWO_TITLE=setup_step_title,
            SETUP_STEP_TWO_BODY=setup_step_body,
            INSTALL_HELPER_HTML=install_helper,
        )
    )


@router.get(APP_DOWNLOAD_DMG_ROUTE)
@router.get(APP_DOWNLOAD_ZIP_ROUTE)
def app_download(request: Request):
    try:
        settings = get_settings()
        source = settings.get_app_download_source(validate=True)
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    if not source:
        raise HTTPException(
            status_code=503,
            detail="App download is not configured yet. Ask Ambient support for the current beta installer.",
        )

    expected_route = settings.get_public_app_download_route(validate=True)
    if request.url.path != expected_route:
        return RedirectResponse(url=expected_route, status_code=307)

    source_kind, source_value = source
    filename = settings.get_app_download_filename(validate=True)
    media_type = settings.get_app_download_media_type(validate=True)
    if source_kind == "file":
        assert isinstance(source_value, Path)
        return FileResponse(
            path=source_value,
            media_type=media_type,
            filename=filename,
        )

    assert isinstance(source_value, str)
    return RedirectResponse(url=source_value, status_code=307)


@router.get("/install.sh")
def install_script():
    return PlainTextResponse(
        _read_static("install.sh")
        .replace("__COORDINATOR_URL__", _public_site_origin())
        .replace(
            "__PUBLIC_WORKER_ENROLLMENT_ENABLED__",
            "1" if get_settings().public_worker_enrollment_enabled else "0",
        ),
        media_type="text/x-shellscript",
    )


@router.get("/earn", response_class=HTMLResponse)
def earn_page():
    return _load_template("earn.html")


@router.get("/trust", response_class=HTMLResponse)
def trust_page():
    return _load_template("trust.html")


@router.get("/terms", response_class=HTMLResponse)
def terms_page():
    return _load_template("terms.html")


@router.get("/privacy", response_class=HTMLResponse)
def privacy_page():
    return _load_template("privacy.html")


@router.get("/worker-agreement", response_class=HTMLResponse)
def worker_agreement_page():
    return _load_template("worker-agreement.html")


@router.get("/manager/login", response_class=HTMLResponse)
def manager_login_page():
    return _load_template("manager_login.html")


@router.get("/manager", response_class=HTMLResponse)
def manager_page(request: Request):
    if not get_current_admin(request):
        return RedirectResponse(url="/manager/login", status_code=303)

    return _load_template("manager.html")


@lru_cache(maxsize=16)
def _read_template(name: str) -> str:
    return (TEMPLATE_ROOT / name).read_text(encoding="utf-8")


@lru_cache(maxsize=8)
def _read_static(name: str) -> str:
    return (STATIC_ROOT / name).read_text(encoding="utf-8")


def _load_template(name: str) -> HTMLResponse:
    return HTMLResponse(_read_template(name))


def _render_template(name: str, **replacements: str) -> str:
    rendered = _read_template(name)
    for key, value in replacements.items():
        rendered = rendered.replace(f"__{key}__", value)
    return rendered


def _public_site_origin() -> str:
    return get_settings().get_manager_origins()[0].rstrip("/")
