import subprocess

from src.domain.hosting.routing_contract import RoutingContractError, compile_routing_manifest


def test_catalog_compiles_cloud_mappings_and_keeps_password_bff_owned():
    manifest = compile_routing_manifest()
    users = {row["id"]: row for row in manifest if row["id"].startswith("auth.users")}

    assert users["auth.users_list"]["owner"] == "cloud"
    assert users["auth.users_list"]["upstream_path"] == "/v1/projects/:project_id/auth/users"
    assert users["auth.users_set_password"]["owner"] == "bff"
    assert users["auth.users_set_password"]["upstream_path"] is None


def test_more_specific_routes_are_sorted_before_their_parent():
    manifest = compile_routing_manifest({
        "ports": [
            {"port_id": "parent", "cloud": {"path": "/v1/projects/:project_id/x"}, "bff": {"method": "GET", "path": "/api/x"}},
            {"port_id": "child", "cloud": {"path": "/v1/projects/:project_id/x/:id"}, "bff": {"method": "GET", "path": "/api/x/:id"}},
        ]
    })
    assert [row["id"] for row in manifest] == ["child", "parent"]


def test_duplicate_method_and_path_is_rejected():
    catalog = {"ports": [
        {"port_id": "one", "cloud": {"path": "/v1/projects/:project_id/x"}, "bff": {"method": "GET", "path": "/api/x"}},
        {"port_id": "two", "cloud": {"path": "/v1/projects/:project_id/y"}, "bff": {"method": "GET", "path": "/api/x"}},
    ]}
    try:
        compile_routing_manifest(catalog)
    except RoutingContractError as exc:
        assert "ambiguous" in str(exc)
    else:
        raise AssertionError("duplicate route registration was accepted")


def test_manifest_forwards_health_and_unknown_api_to_cloud_after_real_ports():
    from src.domain.hosting.routing_contract import compile_application_runtime_manifest

    manifest = compile_routing_manifest()
    by_id = {row["id"]: row for row in manifest}
    health = by_id["diagnostics.health"]
    unknown = by_id["diagnostics.unknown"]
    assert health["owner"] == "cloud"
    assert health["method"] == "GET"
    assert health["public_path"] == "/api/__p2hs/health"
    assert health["upstream_path"] == "/v1/projects/:project_id/__p2hs/health"
    assert unknown["owner"] == "cloud"
    assert unknown["method"] == "*"
    assert unknown["public_path"] == "/api/:path*"
    assert manifest[-1]["id"] == "diagnostics.unknown"
    assert manifest.index(health) < manifest.index(unknown)
    assert any(row["public_path"] == "/api/auth/me" and row["owner"] == "cloud" for row in manifest)
    runtime_ids = {row["id"] for row in compile_application_runtime_manifest()}
    assert "diagnostics.health" not in runtime_ids
    assert "diagnostics.unknown" not in runtime_ids


def test_lifecycle_capabilities_have_no_generated_app_ports():
    import json
    from src.domain.hosting.routing_contract import CATALOG_PATH

    catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
    ids = [row["port_id"] for row in catalog["ports"]]
    assert not any(port_id.startswith(("notification.", "webhook.", "secret.")) for port_id in ids)


def test_dispatcher_keeps_existing_hostnames_on_the_cloud_proxy():
    from src.domain.hosting.routing_plane import CloudflareRoutingProvider

    provider = CloudflareRoutingProvider.__new__(CloudflareRoutingProvider)
    source = provider._dispatcher_source("p2hsapp.com")
    assert 'route.api_execution !== "project_runtime"' in source
    assert source.index("api_execution") < source.index('entry.owner === "cloud"')
    assert "p2hsPromoteSessionHeaders(fwdHeaders)" in source
    assert "return p2hsConsumeMagicLink" in source
    assert source.index("return p2hsConsumeMagicLink") < source.index('route.api_execution !== "project_runtime"')
    assert "p2hsExposeCookies" in source
    assert "new Headers(response.headers)" not in source


def test_dispatcher_contains_gated_manifest_and_no_api_ownership_shortcut():
    from src.domain.hosting.routing_plane import CloudflareRoutingProvider

    provider = CloudflareRoutingProvider.__new__(CloudflareRoutingProvider)
    source = provider._dispatcher_source("p2hsapp.com")
    assert "routing_policy:" in source
    assert 'entry.owner === "cloud"' in source
    assert 'entry.owner === "bff"' in source
    assert 'cloud_route_unavailable' in source


def test_generated_dispatcher_is_valid_javascript():
    from src.domain.hosting.routing_plane import CloudflareRoutingProvider

    provider = CloudflareRoutingProvider.__new__(CloudflareRoutingProvider)
    source = provider._dispatcher_source("p2hsapp.com")
    script = "import { readFileSync } from 'node:fs'; await import('data:text/javascript,' + encodeURIComponent(readFileSync(0, 'utf8')));"
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script],
        input=source,
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr
