"""The generated-app browser client contract: p2hs-app-client.js is the one stable
client surface; framework wrappers (useP2hs.ts today) must depend on it rather than
defining their own transport, and every one of its calls must stay same-origin
/api/* so the client works unmodified under either hosting provider (W4P + shared
BFF or legacy Pages) -- see src.domain.hosting.runtime_projection.
"""
from __future__ import annotations

import re
from pathlib import Path

from src.domain.codegen.runtime_client_contract import (
    RUNTIME_CLIENT_FRAMEWORK_WRAPPER,
    RUNTIME_CLIENT_SOURCE,
    all_contract_exports,
    namespace_for,
)

REPO_ROOT = Path(__file__).resolve().parent.parent

_EXPORT_FUNCTION_RE = re.compile(r"export\s+(?:async\s+)?function\s+([A-Za-z0-9_]+)")
_EXPORT_CLASS_RE = re.compile(r"export\s+class\s+([A-Za-z0-9_]+)")
_REQUEST_CALL_RE = re.compile(r"\b(?:request|fetch)\(\s*(`[^`]*`|\"[^\"]*\"|'[^']*')")


def _client_source() -> str:
    return (REPO_ROOT / RUNTIME_CLIENT_SOURCE).read_text(encoding="utf-8")


def _real_exported_functions(source: str) -> set[str]:
    return set(_EXPORT_FUNCTION_RE.findall(source))


def test_contract_registry_matches_every_real_exported_function():
    """Every function the real client exports is registered in exactly one
    namespace, and the registry names nothing the client doesn't actually export
    -- catches an unregistered addition or a silently-removed function."""
    source = _client_source()
    real_exports = _real_exported_functions(source)

    assert real_exports == all_contract_exports()


def test_every_registered_export_resolves_to_exactly_one_namespace():
    for export_name in all_contract_exports():
        assert namespace_for(export_name) is not None


def test_client_calls_are_same_origin_api_paths_only():
    """Nothing in the common client may call an absolute URL or a Cloud/provider
    host directly -- that's the whole point of routing every capability through
    same-origin /api/*, so the client works unmodified under W4P or Pages."""
    source = _client_source()
    literal_targets = _REQUEST_CALL_RE.findall(source)

    assert literal_targets, "expected to find request()/fetch() calls to check"
    for literal in literal_targets:
        body = literal[1:-1]  # strip the quote/backtick
        assert body.startswith("/api/"), f"non-same-origin call target: {literal}"
        assert "://" not in body, f"absolute URL in client call target: {literal}"


def test_framework_wrapper_only_re_exports_the_common_client():
    """useP2hs.ts must not define its own fetch/transport logic -- it exists only
    to hand the common client's exports to a framework component."""
    wrapper_source = (REPO_ROOT / RUNTIME_CLIENT_FRAMEWORK_WRAPPER).read_text(encoding="utf-8")

    assert "fetch(" not in wrapper_source
    assert "/api/" not in wrapper_source
    assert "p2hs-app" in wrapper_source
