"""Versioned contract for the P2HS Generated App Base Runtime.

The generated W4P Worker is this runtime plus the customer's own BFF routes.
It is one platform client: auth and session bridging, catalog adapters, error
normalization, idempotency, correlation, and an Edge Functions facade.

Cloud executes records, files, queues, providers, webhooks, schedules, and
function workers, and it measures that execution. Core authorizes, reserves,
finalizes, releases, and bills. This runtime does not grow a second copy of
either plane.
"""

from __future__ import annotations

BASE_RUNTIME_CONTRACT = "p2hs-generated-app-base"
BASE_RUNTIME_VERSION = "2"
RUNTIME_NAME = "p2hs-application-runtime"

# One runtime implements these adapters. They are clients, not engines.
BASE_RUNTIME_CAPABILITIES = (
    "auth.session",
    "forms.client",
    "records.client",
    "files.client",
    "bookings.client",
    "jobs.client",
    "errors.normalize",
    "idempotency",
    "correlation",
    "edge_functions.facade",
)

# Present in the runtime source means a second authority was embedded.
FORBIDDEN_RUNTIME_MARKERS = (
    "env.CLOUD_SERVICE_TOKEN",
    "env.FUNCTIONS",
    "INTERNAL_CONTROL_TOKEN",
    "/v1/cloud/authorize",
    "/v1/cloud/usage/finalize",
    "/v1/cloud/usage/release",
    "/v1/cloud/control/",
    "env.DB",
    "env.QUEUE",
    "env.R2",
)

# Unlocked customer routes must call platform.call, not a private Cloud client.
FORBIDDEN_CUSTOMER_MARKERS = (
    ("CLOUD_SERVICE_TOKEN", "second_cloud_client"),
    ("CLOUD_GATEWAY_URL", "second_cloud_client"),
    ("cloudServiceToken", "second_cloud_client"),
    ("cloudGatewayUrl", "second_cloud_client"),
    ("/v1/cloud/", "cloud_control_plane"),
    ("/v1/projects/", "direct_cloud_route"),
    ("INTERNAL_CONTROL_TOKEN", "cloud_control_plane"),
    ("usage/finalize", "billing_authority"),
    ("usage/release", "billing_authority"),
    ("env.FUNCTIONS", "edge_function_execution"),
    ("eval(", "local_code_execution"),
    ("new Function(", "local_code_execution"),
)

# The app Worker routes these. Isolated function workers execute them.
EDGE_FUNCTION_ROUTES = (
    {
        "id": "functions.invoke",
        "method": "POST",
        "public_path": "/api/fn/:slug",
        "auth": "session",
        "upstream_path": "/v1/projects/:project_id/fn/:slug",
        "invocation": "production",
    },
    {
        "id": "functions.test",
        "method": "POST",
        "public_path": "/api/fn/:slug/test",
        "auth": "session",
        "upstream_path": "/v1/projects/:project_id/fn/:slug/test",
        "invocation": "test",
    },
)


def assert_runtime_contract(runtime: str, entry: str) -> None:
    """Fail the Worker build when the base runtime crosses its boundary."""
    for marker in FORBIDDEN_RUNTIME_MARKERS:
        if marker in runtime or marker in entry:
            raise RuntimeError(f"generated app base runtime contains {marker}")
    if BASE_RUNTIME_CONTRACT not in runtime or RUNTIME_NAME not in runtime:
        raise RuntimeError("base runtime contract identity missing")
    if f'"{BASE_RUNTIME_VERSION}"' not in runtime:
        raise RuntimeError("base runtime contract version missing")
    for capability in BASE_RUNTIME_CAPABILITIES:
        if capability not in runtime:
            raise RuntimeError(f"base runtime capability missing: {capability}")
    facade = entry.find('path === "/api/fn"')
    dispatch = entry.find("dispatchApplication")
    if facade < 0 or dispatch < 0 or facade > dispatch:
        raise RuntimeError("edge function facade must route before application dispatch")
