"""Portable application runtime: credential forwarding, health, and version retention."""

import json
import subprocess

from src.domain.hosting.adapters.w4p_static import version_scripts_to_delete
from src.domain.hosting.runtime.worker_source import build_worker_source
from src.domain.hosting.w4p_activation import runtime_health_decision
from src.domain.hosting.w4p_workflow import W4P_UPLOAD_SCRIPT


def test_worker_source_is_shared_and_does_not_upgrade_sessions():
    source = build_worker_source([
        {"id": "records.query", "method": "POST", "public_path": "/api/records/:entity/query", "auth": "session", "upstream_path": "/v1/projects/:project_id/records/:entity/query"},
    ])
    assert "env.ASSETS.fetch" in source
    assert "handleApiRequest" in source
    assert "env.CLOUD_SERVICE_TOKEN" not in source
    assert "handleApiRequest" in W4P_UPLOAD_SCRIPT
    assert "env.ASSETS.fetch" in W4P_UPLOAD_SCRIPT
    assert "env.CLOUD_SERVICE_TOKEN" not in W4P_UPLOAD_SCRIPT
    result = subprocess.run(
        ["node", "--input-type=module", "-e", "import { readFileSync } from 'node:fs'; await import('data:text/javascript,' + encodeURIComponent(readFileSync(0, 'utf8')));"],
        input=source,
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr


def test_runtime_forwards_the_caller_cookie_and_hides_the_gateway():
    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const seen = [];
const fetchImpl = async (url, init) => {
  seen.push({ url, authorization: init.headers.get('authorization') || '', cookie: init.headers.get('cookie') || '' });
  return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'content-type': 'application/json' } });
};
const env = { PROJECT_ID: 'project-1', CLOUD_GATEWAY_URL: 'https://cloud.example', CLOUD_SERVICE_TOKEN: 'super-secret' };
const health = await mod.handleApiRequest(new Request('https://prev-abc.p2hsapp.com/api/__p2hs/health'), env, { fetchImpl, routes: [] });
const healthBody = await health.text();
if (healthBody.includes('cloud.example') || healthBody.includes('super-secret')) process.exit(2);
const staff = await mod.handleApiRequest(new Request('https://prev-abc.p2hsapp.com/api/admin/users', { headers: { cookie: '__Host-p2hs_access=user-token' } }), env, { fetchImpl, routes: JSON.parse(process.argv[2]) });
if (!staff.ok) process.exit(3);
const dynamic = await mod.handleApiRequest(new Request('https://prev-abc.p2hsapp.com/api/new/catalog-port'), env, { fetchImpl, routes: [] });
if (dynamic.status !== 200) process.exit(4);
const forwarded = seen[0];
if (!forwarded.cookie.includes('user-token')) process.exit(5);
if (forwarded.authorization.includes('super-secret')) process.exit(6);
if (!forwarded.url.includes('/v1/projects/project-1/auth/users')) process.exit(7);
if (!seen[1].url.includes('/v1/projects/project-1/runtime/api/new/catalog-port')) process.exit(8);
process.stdout.write('ok');
"""
    routes = [
        {"id": "auth.users_list", "method": "GET", "public_path": "/api/admin/users", "auth": "staff", "upstream_path": "/v1/projects/:project_id/auth/users"},
    ]
    # runtime_source prepends the session bridge. The runtime file alone does not
    # define p2hsPromoteSessionHeaders.
    from src.domain.hosting.runtime.worker_source import runtime_source
    runtime = runtime_source()
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, runtime, json.dumps(routes)],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_magic_consume_never_exposes_the_session_to_browser_readable_storage():
    """AUTH-1 regression test. The session is an HttpOnly cookie only; nothing
    in the handoff response may let JavaScript read or persist a live
    access/refresh token (localStorage, sessionStorage, document.cookie, or a
    non-HttpOnly cookie), since that token would then be stealable by any XSS
    in the generated app. See src/domain/codegen/runtime/p2hs-app-client.js,
    which never reads a token out of browser storage either."""
    from src.domain.hosting.runtime.worker_source import runtime_source

    runtime = runtime_source()
    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const fetchImpl = async () => new Response(JSON.stringify({
  access_token: 'access-1',
  refresh_token: 'refresh-1',
}), { status: 200, headers: { 'content-type': 'application/json' } });
const env = { PROJECT_ID: 'project-1', CLOUD_GATEWAY_URL: 'https://cloud.example' };
const response = await mod.handleApiRequest(
  new Request('https://prev-abc.p2hsapp.com/api/auth/magic-link/consume?token=magic&next=/admin'),
  env,
  { fetchImpl, routes: [] },
);
const html = await response.text();
const cookies = response.headers.getSetCookie?.() || [];
if (!cookies.some((item) => item.includes('__Host-p2hs_access=') && item.includes('HttpOnly'))) process.exit(2);
if (!cookies.some((item) => item.includes('__Host-p2hs_refresh=') && item.includes('HttpOnly'))) process.exit(9);
if (cookies.some((item) => !item.startsWith('__Host-p2hs_access') && !item.startsWith('__Host-p2hs_refresh'))) process.exit(10);
if (!response.headers.get('cache-control').includes('private') || !response.headers.get('cache-control').includes('no-store')) process.exit(6);
if (response.headers.get('cdn-cache-control') !== 'no-store') process.exit(7);
if (response.headers.get('cloudflare-cdn-cache-control') !== 'no-store') process.exit(8);
if (html.includes('access-1') || html.includes('refresh-1')) process.exit(3);
if (html.includes('localStorage') || html.includes('sessionStorage') || html.includes('document.cookie')) process.exit(11);
if (html.includes('access_token') || html.includes('refresh_token') || html.includes('p2hs_auth_session')) process.exit(12);
if (!html.includes('location.replace')) process.exit(4);
process.stdout.write('ok');
"""
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, runtime],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_cookie_session_is_promoted_and_refresh_is_replayed_into_the_body():
    """W4P drops Cookie on the Cloud subrequest and still forwards Authorization.
    A magic-link session has no bearer until the edge promotes the access cookie.
    Refresh has the same hole: the app posts an empty body and expects the
    refresh cookie to authorize the call."""
    from src.domain.hosting.runtime.worker_source import runtime_source

    runtime = runtime_source()
    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const seen = [];
const fetchImpl = async (url, init) => {
  seen.push({
    url,
    authorization: init.headers.get('authorization') || '',
    cookie: init.headers.get('cookie') || '',
    body: init.body ? await new Response(init.body).text() : '',
  });
  return new Response(JSON.stringify({ user: { id: 'user-1' } }), { status: 200, headers: { 'content-type': 'application/json' } });
};
const env = { PROJECT_ID: 'project-1', CLOUD_GATEWAY_URL: 'https://cloud.example' };
const routes = JSON.parse(process.argv[2]);
const me = await mod.handleApiRequest(new Request('https://prev-abc.p2hsapp.com/api/auth/me', {
  headers: { cookie: '__Host-p2hs_access=access-1; __Host-p2hs_refresh=refresh-1' },
}), env, { fetchImpl, routes });
if (!me.ok) process.exit(2);
if (seen[0].authorization !== 'Bearer access-1') process.exit(3);
if (!seen[0].cookie.includes('__Host-p2hs_access=access-1')) process.exit(4);
const kept = await mod.handleApiRequest(new Request('https://prev-abc.p2hsapp.com/api/auth/me', {
  headers: { cookie: '__Host-p2hs_access=access-1', authorization: 'Bearer caller-token' },
}), env, { fetchImpl, routes });
if (!kept.ok || seen[1].authorization !== 'Bearer caller-token') process.exit(5);
const refresh = await mod.handleApiRequest(new Request('https://prev-abc.p2hsapp.com/api/auth/refresh', {
  method: 'POST',
  headers: { cookie: '__Host-p2hs_refresh=refresh-1', 'content-type': 'application/json' },
  body: '{}',
}), env, { fetchImpl, routes });
if (!refresh.ok) process.exit(6);
const posted = JSON.parse(seen[2].body);
if (posted.refresh_token !== 'refresh-1') process.exit(7);
process.stdout.write('ok');
"""
    routes = [
        {"id": "auth.session", "method": "GET", "public_path": "/api/auth/me", "auth": "session", "upstream_path": "/v1/projects/:project_id/auth/me"},
        {"id": "auth.refresh", "method": "POST", "public_path": "/api/auth/refresh", "auth": "public", "upstream_path": "/v1/projects/:project_id/auth/refresh"},
    ]
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, runtime, json.dumps(routes)],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_rebuilt_responses_keep_every_session_cookie():
    from src.domain.hosting.runtime.worker_source import session_bridge_source

    script = """
const bridge = process.argv[1];
await import('data:text/javascript,' + encodeURIComponent(bridge + `
globalThis.__bridge = { p2hsExposeCookies, p2hsCloneResponseHeaders };
`));
const headers = new Headers({ 'content-type': 'text/html' });
headers.append('set-cookie', '__Host-p2hs_access=access-1; Path=/; HttpOnly; Secure');
headers.append('set-cookie', '__Host-p2hs_refresh=refresh-1; Path=/; HttpOnly; Secure');
const exposed = globalThis.__bridge.p2hsExposeCookies(new Response('ok', { status: 200, headers }));
const cookies = exposed.headers.getSetCookie();
if (cookies.length !== 2) process.exit(2);
if (!cookies.some((item) => item.includes('__Host-p2hs_access=access-1'))) process.exit(3);
if (!cookies.some((item) => item.includes('__Host-p2hs_refresh=refresh-1'))) process.exit(4);
const cloned = globalThis.__bridge.p2hsCloneResponseHeaders(headers);
cloned.append('set-cookie', '__p2hs_ve=1; Path=/');
const kept = cloned.getSetCookie();
if (kept.length !== 3) process.exit(5);
process.stdout.write('ok');
"""
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, session_bridge_source()],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_token_login_and_oauth_callback_become_http_only_cookie_sessions():
    from src.domain.hosting.runtime.worker_source import runtime_source

    runtime = runtime_source()
    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const fetchImpl = async () => new Response(JSON.stringify({ access_token: 'access-1', refresh_token: 'refresh-1' }), { status: 200, headers: { 'content-type': 'application/json' } });
const env = { PROJECT_ID: 'project-1', CLOUD_GATEWAY_URL: 'https://cloud.example' };
const routes = [{ id: 'auth.signin', method: 'POST', public_path: '/api/auth/signin', auth: 'public', upstream_path: '/v1/projects/:project_id/auth/signin' }];
const signIn = await mod.handleApiRequest(new Request('https://app.example/api/auth/signin', { method: 'POST', body: '{}', headers: { 'content-type': 'application/json' } }), env, { fetchImpl, routes });
const loginCookies = signIn.headers.getSetCookie();
if (loginCookies.length !== 2 || !loginCookies.some((v) => v.includes('__Host-p2hs_access=access-1')) || !loginCookies.some((v) => v.includes('__Host-p2hs_refresh=refresh-1'))) process.exit(2);
const callback = await mod.handleApiRequest(new Request('https://app.example/api/auth/oauth/callback?access_token=oauth-a&refresh_token=oauth-r&next=%2Flogin'), env, { fetchImpl, routes });
if (callback.status !== 302 || callback.headers.get('location') !== '/login') process.exit(3);
const oauthCookies = callback.headers.getSetCookie();
if (oauthCookies.length !== 2 || !oauthCookies.some((v) => v.includes('__Host-p2hs_access=oauth-a')) || !oauthCookies.some((v) => v.includes('__Host-p2hs_refresh=oauth-r'))) process.exit(4);
process.stdout.write('ok');
"""
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, runtime],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_generated_client_exposes_google_oauth_handoff_without_token_storage():
    from pathlib import Path

    client = Path("src/domain/codegen/runtime/p2hs-app-client.js").read_text(encoding="utf-8")
    assert "signInWithGoogle" in client
    assert "/api/auth/oauth/google" in client
    assert "/api/auth/oauth/callback" in client
    assert "localStorage" not in client


def test_codegen_magic_link_template_never_exposes_the_session_either():
    """Same AUTH-1 guard, for the codegen-emitted template that generated
    Pages-Functions-era apps still ship (src/domain/codegen/runtime/p2hs-auth-magic.mjs),
    so the two copies of this handoff logic can't drift apart again."""
    from pathlib import Path

    source = Path("src/domain/codegen/runtime/p2hs-auth-magic.mjs").read_text(encoding="utf-8")
    assert "localStorage" not in source
    assert "sessionStorage" not in source
    assert "document.cookie" not in source
    assert "p2hs_auth_session" not in source
    assert "P2HS_ACCESS_COOKIE" in source and "HttpOnly" in source


def test_w4p_runtime_adapts_record_query_and_application_files():
    source = build_worker_source([
        {"id": "records.query", "method": "POST", "public_path": "/api/records/:entity/query", "auth": "session", "upstream_path": "/v1/projects/:project_id/records/query"},
    ])
    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const seen = [];
const fetchImpl = async (url, init) => {
  seen.push({ url, body: init.body ? await new Response(init.body).text() : '' });
  return new Response(JSON.stringify({ records: [], next_cursor: null }), { status: 200, headers: { 'content-type': 'application/json' } });
};
const env = { PROJECT_ID: 'project-1', CLOUD_GATEWAY_URL: 'https://cloud.example' };
await mod.handleApiRequest(new Request('https://proj-x.p2hsapp.com/api/records/orders/query', { method: 'POST', headers: { authorization: 'Bearer user', 'content-type': 'application/json' }, body: JSON.stringify({ limit: 1 }) }), env, { fetchImpl, routes: JSON.parse(process.argv[2]) });
await mod.handleApiRequest(new Request('https://proj-x.p2hsapp.com/api/files', { method: 'POST', headers: { authorization: 'Bearer user', 'content-type': 'application/json' }, body: JSON.stringify({ filename: 'a.txt', content_base64: 'YQ==' }) }), env, { fetchImpl, routes: JSON.parse(process.argv[2]) });
if (!seen[0].body.includes('"entity_key":"orders"')) process.exit(2);
if (!seen[1].url.includes('/application-files')) process.exit(3);
process.stdout.write('ok');
""";
    import json
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, source, json.dumps([
            {"id": "records.query", "method": "POST", "public_path": "/api/records/:entity/query", "auth": "session", "upstream_path": "/v1/projects/:project_id/records/query"},
            {"id": "application.files.upload", "method": "POST", "public_path": "/api/files", "auth": "session", "upstream_path": "/v1/projects/:project_id/application-files"},
        ])],
        capture_output=True, text=True, encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_version_cleanup_keeps_live_previous_and_referenced_scripts():
    names = [
        "p2hs-prod-abc-v11111111",
        "p2hs-prod-abc-v22222222",
        "p2hs-prod-abc-v33333333",
        "p2hs-prod-other-v11111111",
        "p2hs-dispatcher",
    ]
    doomed = version_scripts_to_delete(
        names,
        prefix="p2hs-prod-abc",
        keep={"p2hs-prod-abc-v33333333", "p2hs-prod-abc-v22222222"},
    )
    assert doomed == ["p2hs-prod-abc-v11111111"]


def test_base_runtime_advertises_its_contract_and_keeps_authorization_status():
    from src.domain.hosting.runtime.base_runtime_contract import (
        BASE_RUNTIME_CAPABILITIES,
        BASE_RUNTIME_CONTRACT,
        BASE_RUNTIME_VERSION,
    )
    from src.domain.hosting.runtime.worker_source import runtime_source

    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const seen = [];
const fetchImpl = async (url, init) => {
  seen.push({
    url: String(url),
    requestId: init.headers.get('x-request-id') || '',
    correlation: init.headers.get('x-p2hs-correlation-id') || '',
    idempotency: init.headers.get('idempotency-key') || '',
    invocation: init.headers.get('x-p2hs-invocation') || '',
  });
  const target = String(url);
  if (target.endsWith('/deny')) {
    return new Response(JSON.stringify({ error: 'forbidden', message: 'https://cloud.example/policy' }), {
      status: 403,
      headers: { 'content-type': 'application/json' },
    });
  }
  if (target.endsWith('/auth-deny')) {
    return new Response(JSON.stringify({ error: 'unauthorized', message: 'missing_token' }), {
      status: 401,
      headers: { 'content-type': 'application/json' },
    });
  }
  return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'content-type': 'application/json' } });
};
const env = { PROJECT_ID: 'project-1', CLOUD_GATEWAY_URL: 'https://cloud.example' };
const routes = JSON.parse(process.argv[2]);
const health = await mod.handleApiRequest(new Request('https://app.example/api/__p2hs/health'), env, { fetchImpl, routes });
const healthBody = await health.json();
if (healthBody.contract !== process.argv[3] || healthBody.contract_version !== process.argv[4]) process.exit(2);
if (JSON.stringify(healthBody.capabilities) !== JSON.stringify(JSON.parse(process.argv[5]))) process.exit(3);
if (JSON.stringify(healthBody).includes('cloud.example')) process.exit(4);
const denied = await mod.handleApiRequest(new Request('https://app.example/api/probe/deny'), env, { fetchImpl, routes });
const deniedBody = await denied.json();
if (denied.status !== 403 || deniedBody.error !== 'forbidden' || JSON.stringify(deniedBody).includes('cloud.example')) process.exit(5);
const authDenied = await mod.handleApiRequest(new Request('https://app.example/api/probe/auth-deny', {
  headers: { 'x-request-id': 'req_caller_1', 'idempotency-key': 'job-1' },
}), env, { fetchImpl, routes });
const authBody = await authDenied.json();
if (authDenied.status !== 401 || authBody.message !== 'missing_token') process.exit(6);
if (authDenied.headers.get('x-request-id') !== 'req_caller_1') process.exit(7);
if (seen[1].requestId !== 'req_caller_1' || seen[1].correlation !== 'req_caller_1' || seen[1].idempotency !== 'job-1') process.exit(8);
const invoked = await mod.handleApiRequest(new Request('https://app.example/api/fn/send-email', { method: 'POST', body: '{}' }), env, { fetchImpl, routes });
if (!invoked.ok || !seen[2].url.endsWith('/v1/projects/project-1/fn/send-email') || seen[2].invocation !== 'production') process.exit(9);
const tested = await mod.handleApiRequest(new Request('https://app.example/api/fn/send-email/test', { method: 'POST', body: '{}' }), env, { fetchImpl, routes });
if (!tested.ok || !seen[3].url.endsWith('/v1/projects/project-1/fn/send-email/test') || seen[3].invocation !== 'test') process.exit(10);
const wrongMethod = await mod.handleApiRequest(new Request('https://app.example/api/fn/send-email'), env, { fetchImpl, routes });
if (wrongMethod.status !== 405) process.exit(11);
process.stdout.write('ok');
"""
    routes = [
        {"id": "probe.deny", "method": "GET", "public_path": "/api/probe/deny", "auth": "public", "upstream_path": "/v1/projects/:project_id/deny"},
        {"id": "probe.auth", "method": "GET", "public_path": "/api/probe/auth-deny", "auth": "session", "upstream_path": "/v1/projects/:project_id/auth-deny"},
    ]
    result = subprocess.run(
        [
            "node", "--input-type=module", "-e", script, runtime_source(), json.dumps(routes),
            BASE_RUNTIME_CONTRACT, BASE_RUNTIME_VERSION, json.dumps(list(BASE_RUNTIME_CAPABILITIES)),
        ],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_platform_call_inherits_caller_session_and_request_metadata():
    from src.domain.hosting.runtime.worker_source import runtime_source

    script = """
const mod = await import('data:text/javascript,' + encodeURIComponent(process.argv[1]));
const seen = [];
const fetchImpl = async (url, init) => {
  seen.push({
    authorization: init.headers.get('authorization') || '',
    correlation: init.headers.get('x-p2hs-correlation-id') || '',
    idempotency: init.headers.get('idempotency-key') || '',
  });
  return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'content-type': 'application/json' } });
};
const base = new Request('https://app.example/api/quotes/price', {
  headers: {
    authorization: 'Bearer caller',
    'x-request-id': 'req_from_caller',
    'idempotency-key': 'idem_from_caller',
  },
});
const next = new Request('https://app.example/api/auth/me');
const response = await mod.platformCall(base, next, {
  PROJECT_ID: 'project-1',
  CLOUD_GATEWAY_URL: 'https://cloud.example',
}, {
  fetchImpl,
  routes: [{ id: 'auth.me', method: 'GET', public_path: '/api/auth/me', auth: 'session', upstream_path: '/v1/projects/:project_id/auth/me' }],
});
if (!response.ok) process.exit(2);
if (seen[0].authorization !== 'Bearer caller') process.exit(3);
if (seen[0].correlation !== 'req_from_caller') process.exit(4);
if (seen[0].idempotency !== 'idem_from_caller') process.exit(5);
process.stdout.write('ok');
"""
    result = subprocess.run(
        ["node", "--input-type=module", "-e", script, runtime_source()],
        capture_output=True,
        text=True,
        encoding="utf-8",
    )
    assert result.returncode == 0, result.stderr or result.stdout


def test_edge_function_facade_skips_application_code():
    from src.domain.hosting.runtime.worker_source import runtime_source, worker_entry

    prelude = """
async function dispatchApplication() {
  return Response.json({ owner: "application-executed-function" });
}
"""
    source = "\n".join((runtime_source().rstrip(), prelude.strip(), worker_entry([]).lstrip()))
    script = """
import { readFileSync } from 'node:fs';
const mod = await import('data:text/javascript,' + encodeURIComponent(readFileSync(process.argv[1], 'utf8')));
const seen = [];
globalThis.fetch = async (url) => {
  seen.push(String(url));
  return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { 'content-type': 'application/json' } });
};
const env = {
  ASSETS: { fetch: async () => new Response('asset') },
  PROJECT_ID: 'project-1',
  CLOUD_GATEWAY_URL: 'https://cloud.example',
};
const response = await mod.default.fetch(new Request('https://proj.example/api/fn/send-email', { method: 'POST', body: '{}' }), env, {});
const body = await response.text();
if (body.includes('application-executed-function')) process.exit(2);
if (!seen.some((url) => url.endsWith('/v1/projects/project-1/fn/send-email'))) process.exit(3);
if (body.includes('cloud.example')) process.exit(4);
process.stdout.write('ok');
"""
    import tempfile
    from pathlib import Path

    with tempfile.NamedTemporaryFile("w", suffix=".mjs", delete=False, encoding="utf-8") as handle:
        handle.write(source)
        source_path = handle.name
    try:
        result = subprocess.run(
            ["node", "--input-type=module", "-e", script, source_path],
            capture_output=True,
            text=True,
            encoding="utf-8",
        )
    finally:
        Path(source_path).unlink(missing_ok=True)
    assert result.returncode == 0, result.stderr or result.stdout


def test_customer_boundary_matches_the_base_runtime_contract():
    from pathlib import Path

    from src.domain.hosting.runtime.base_runtime_contract import (
        EDGE_FUNCTION_ROUTES,
        FORBIDDEN_CUSTOMER_MARKERS,
        FORBIDDEN_RUNTIME_MARKERS,
    )
    from src.domain.hosting.runtime.worker_source import runtime_source, worker_entry
    from src.domain.hosting.w4p_workflow import W4P_UPLOAD_SCRIPT

    bundler = Path("src/domain/hosting/runtime/bundle_application.mjs").read_text(encoding="utf-8")
    for marker, _code in FORBIDDEN_CUSTOMER_MARKERS:
        assert marker in bundler
    for route in EDGE_FUNCTION_ROUTES:
        assert route["public_path"] in bundler
    # The deployed Worker is the runtime plus the entry. The upload script also
    # embeds the build-time bundler, which names these markers so it can reject them.
    deployed = runtime_source() + worker_entry([])
    for marker in FORBIDDEN_RUNTIME_MARKERS:
        assert marker not in deployed
    assert 'name: "ASSETS", type: "assets"' in W4P_UPLOAD_SCRIPT
    assert 'type: "d1"' not in W4P_UPLOAD_SCRIPT
    assert 'type: "r2_bucket"' not in W4P_UPLOAD_SCRIPT
    assert 'type: "queue"' not in W4P_UPLOAD_SCRIPT


def test_runtime_health_does_not_roll_back_a_cloud_proxy_response():
    assert runtime_health_decision(404, {"error": "not_found"}, "not found") == "pending"
    assert runtime_health_decision(200, {"ok": True, "runtime": "p2hs-application-runtime"}, '{"ok":true}') == "healthy"
    assert runtime_health_decision(200, {"ok": True, "runtime": "p2hs-application-runtime"}, "https://cloudgate.p2hs.com") == "unhealthy"
