"""Per-route API contract results, plus the static-generate checks for the W4P shell."""

from __future__ import annotations

from typing import Any


def compare_contract(expected: dict[str, Any], actual: dict[str, Any] | None) -> dict[str, Any]:
    """Compare method, path, and request/response shape. OpenAPI may supply ``expected``."""
    if expected.get("portable") is False:
        status = (
            "delegated_to_p2hs_cloud"
            if expected.get("customer_chose_cloud")
            else "unavailable_until_external_endpoint"
        )
        return {"status": status, "passing": False, "limitations": list(expected.get("limitations") or [])}
    if not actual:
        return {"status": "unavailable_until_external_endpoint", "passing": False, "limitations": []}
    shape_ok = (
        expected.get("method") == actual.get("method")
        and expected.get("path") == actual.get("path")
        and set(expected.get("request_fields") or []) == set(actual.get("request_fields") or [])
        and set(expected.get("response_fields") or []) == set(actual.get("response_fields") or [])
    )
    limitations = list(actual.get("limitations") or [])
    if not shape_ok:
        return {"status": "unavailable_until_external_endpoint", "passing": False, "limitations": limitations}
    if limitations:
        return {"status": "projected_with_limitations", "passing": True, "limitations": limitations}
    return {"status": "projected_and_verified", "passing": True, "limitations": []}


def build_compatibility_report(routes: list[dict[str, Any]]) -> dict[str, Any]:
    results = []
    for route in routes:
        compared = compare_contract(route.get("expected") or {}, route.get("actual"))
        results.append({"id": route.get("id"), **compared})
    return {
        "routes": results,
        "presented_as_working": [item["id"] for item in results if item["passing"]],
    }


def evaluate_static_generate(
    *,
    generate_succeeded: bool,
    expected_routes: list[str],
    emitted_routes: list[str],
    browser_calls: list[dict[str, str]],
    configured_prefixes: list[str],
    server_only_missing: list[str],
    platform_calls_use_session: bool,
) -> dict[str, Any]:
    """Checks for the static shell. They are not an SSR migration."""
    missing_routes = [route for route in expected_routes if route not in set(emitted_routes)]
    bad_calls = [
        call for call in browser_calls
        if not _uses_prefix(call.get("url") or "", configured_prefixes)
    ]
    checks = [
        {"name": "generate_succeeded", "passed": generate_succeeded},
        {"name": "static_routes_emitted", "passed": not missing_routes, "missing": missing_routes},
        {"name": "browser_calls_use_prefixes", "passed": not bad_calls, "calls": bad_calls},
        {"name": "server_only_data_present", "passed": not server_only_missing, "missing": server_only_missing},
        {"name": "platform_prefix_uses_session", "passed": platform_calls_use_session},
    ]
    return {"ready": all(item["passed"] for item in checks), "checks": checks}


def _uses_prefix(url: str, prefixes: list[str]) -> bool:
    path = url.split("?", 1)[0]
    if path.startswith("/api/_p2hs"):
        return True
    return any(path == prefix or path.startswith(prefix + "/") for prefix in prefixes if prefix and prefix != "/")
