"""Projection of the versioned Cloud-owned contract. Policy is evaluated in Core."""

from __future__ import annotations

import json
from pathlib import Path

CATALOG = json.loads(
    (Path(__file__).with_name("contracts") / "platform-port-catalog.json").read_text(
        encoding="utf-8"
    )
)
CATALOG_VERSION: str = CATALOG["version"]

CONTRACTS = json.loads(
    (Path(__file__).with_name("contracts") / "platform-port-contracts.json").read_text(
        encoding="utf-8"
    )
)["contracts"]
_missing_contracts = [
    p["port_id"] for p in CATALOG["ports"] if p.get("bff") and p["port_id"] not in CONTRACTS
]
if _missing_contracts:
    raise RuntimeError(f"platform-port-contracts.json is missing entries for: {_missing_contracts}")
REQUEST_TYPES = tuple(
    p["cloud"]["request_type"] for p in CATALOG["ports"] if "request_type" in p["cloud"]
)
QUEUE_REQUEST_TYPES = tuple(
    p["cloud"]["request_type"] for p in CATALOG["ports"] if p["cloud"]["transport"] == "queue"
)
_PLATFORM_METADATA_PATHS = frozenset(
    {
        "scripts/p2hs-codegen-action-runner.mjs",
        "p2hs/platform-ports.lock.json",
        "p2hs/cloud-contract.json",
        "p2hs/runtime-contract.json",
        "p2hs/admin-presentation.json",
        "p2hs/app-blocks-plan.json",
        "p2hs/discovery-cloud-contract.json",
        "p2hs/project-state.json",
        "p2hs/project-brief.md",
    }
)
_PLATFORM_RUNTIME_NAMES = frozenset(
    {
        "p2hs-port-contract.mjs",
        "p2hs-ports.mjs",
        "p2hs-app.js",
        "usep2hs.ts",
    }
)


def catalog_bff_paths() -> frozenset[str]:
    """Repo paths the catalog installs. Those are platform projections, not customer edits."""
    found: set[str] = set()
    for port in CATALOG["ports"]:
        files = (port.get("bff") or {}).get("files") or {}
        for value in files.values():
            if isinstance(value, str) and value.strip():
                found.add(value.replace("\\", "/").lstrip("./"))
    return frozenset(found)


_CATALOG_BFF_PATHS = catalog_bff_paths()


def is_platform_projection_path(path: str | None) -> bool:
    """True for catalog routes, adapter libraries, and codegen metadata."""
    normalized = (path or "").replace("\\", "/").strip()
    if normalized.startswith("./"):
        normalized = normalized[2:]
    if not normalized:
        return False
    lowered = normalized.lower()
    if lowered.startswith(".p2hs/") or lowered.startswith(".github/"):
        return True
    if lowered in _PLATFORM_METADATA_PATHS or normalized in _CATALOG_BFF_PATHS:
        return True
    if lowered.startswith("functions/_lib/p2hs-") or lowered.startswith("server/utils/p2hs-"):
        return True
    return lowered.rsplit("/", 1)[-1] in _PLATFORM_RUNTIME_NAMES


def enabled_capabilities(settings: dict) -> set[str]:
    defaults = {
        "query_dsl_v1": True,
        "bulk_import": True,
        "integrations.execute": True,
        "voice.enabled": False,
        "livechat.enabled": False,
    }
    defaults.update(settings.get("cloud_capabilities") or {})
    return {key for key, value in defaults.items() if value is True}


def allowed_request_types(settings: dict) -> set[str]:
    raw = settings.get("cloud_allowed_request_types")
    allowed = set(REQUEST_TYPES) if raw is None else set(raw) if isinstance(raw, list) else set()
    caps = enabled_capabilities(settings)
    if settings.get("cloud_enabled") is False:
        return set()
    return {
        p["cloud"]["request_type"]
        for p in CATALOG["ports"]
        if p["cloud"].get("request_type") in allowed
        and (p["entitlement"] == "cloud" or p["entitlement"] in caps)
    }


def entitled_ports(settings: dict | None = None, plan: str = "free") -> list[dict]:
    settings = settings or {}
    if settings.get("cloud_enabled") is False:
        return []
    caps = enabled_capabilities(settings)
    allowed = allowed_request_types(settings)
    return [
        p
        for p in CATALOG["ports"]
        if p.get("bff")
        and (
            p["entitlement"] == "cloud"
            or p["entitlement"] in caps
            or (p["entitlement"] == "ai" and plan != "free")
        )
        and (not p["cloud"].get("request_type") or p["cloud"]["request_type"] in allowed)
    ]


def api_surface(ports: list[dict]) -> dict:
    surface: dict = {}
    for port in ports:
        group, operation = port["port_id"].split(".", 1)
        surface.setdefault(group, {})[operation] = {
            "port_id": port["port_id"],
            "method": port["bff"]["method"],
            "path": port["bff"]["path"],
            "auth": port["bff"]["auth"],
            "transport": port["cloud"]["transport"],
            "schema": CONTRACTS[port["port_id"]],
        }
    return surface
