"""Public contact BFF helpers for Pages apps (Nuxt, React, HTML).

Inbox, public-config, and magic-link consume stay installed. The unauthenticated
``POST /api/contact`` submit route is compatibility-only: emit it when an existing
project already has that route, not for new canonical Forms projects.
"""
from __future__ import annotations

from pathlib import Path

from src.domain.codegen.legacy_contact_generation import CONTACT_SUBMIT_RELATIVE_PATHS

_PAGES_TYPES = frozenset({"html", "react_app", "nuxt_app"})
ADAPTER_MARKER = "p2hs-contact"


def contact_adapter_files(
    project_type: str,
    runtime_contract: dict | None = None,
    *,
    include_submit_route: bool = True,
) -> dict[str, str]:
    if project_type not in _PAGES_TYPES:
        return {}
    root = Path(__file__).with_name("runtime")
    admin_path = "/admin"
    if runtime_contract:
        admin_path = (runtime_contract.get("routes") or {}).get("admin_panel_path") or "/admin"
    shared = (root / "p2hs-contact.mjs").read_text(encoding="utf-8")
    files = {
        "functions/_lib/p2hs-contact.mjs": shared,
        "functions/_lib/p2hs-auth-magic.mjs": (root / "p2hs-auth-magic.mjs")
        .read_text(encoding="utf-8")
        .replace("__P2HS_ADMIN_PANEL_PATH__", admin_path),
        "functions/api/contact.js": (root / "contact-pages-fn.js").read_text(encoding="utf-8"),
        "functions/api/contact/inbox.js": (root / "contact-inbox-pages-fn.js").read_text(
            encoding="utf-8"
        ),
        "functions/api/public-config.js": (root / "public-config-pages-fn.js").read_text(
            encoding="utf-8"
        ),
        "functions/api/auth/magic-link/consume.js": (
            root / "magic-consume-pages-fn.js"
        ).read_text(encoding="utf-8"),
    }
    if project_type == "nuxt_app":
        files["server/utils/p2hs-contact.mjs"] = shared
        files["server/utils/p2hs-auth-magic.mjs"] = files["functions/_lib/p2hs-auth-magic.mjs"]
        files["server/api/contact.post.ts"] = (root / "contact-route.ts").read_text(
            encoding="utf-8"
        )
        files["server/api/contact/inbox.get.ts"] = (
            root / "contact-inbox-route.ts"
        ).read_text(encoding="utf-8")
        files["server/api/public-config.get.ts"] = (
            root / "public-config-route.ts"
        ).read_text(encoding="utf-8")
        files["server/api/auth/magic-link/consume.get.ts"] = (
            root / "magic-consume-route.ts"
        ).read_text(encoding="utf-8")
    if not include_submit_route:
        for rel in CONTACT_SUBMIT_RELATIVE_PATHS:
            files.pop(rel, None)
    return files
