"""Doc scenario Test C -- custom admin route + magic link (Core side).

Given: admin route is /be-admin; admin auth is magic link.
Expect: every generated artifact resolves to /be-admin, never /admin -- and the guard
that would catch a regression accepts the actual files this chain just produced.

Cloud-side (magicNextPath/authLinkPath landing under /be-admin) is covered in
apps/pc-gateway/src/lib/app-origin.test.ts, not here -- this file is what Core controls.
"""
from __future__ import annotations

import json
import tempfile
from pathlib import Path

from src.domain.codegen.app_sdk import app_sdk_files, staff_shell_files
from src.domain.codegen.backend_guard import validate_backend_repo
from src.domain.codegen.contact_adapter import contact_adapter_files
from src.domain.projects.runtime_invariants import ProjectRuntimeInvariants, extract_runtime_invariants


def _contract_dict(invariants: ProjectRuntimeInvariants) -> dict:
    return {
        "routes": {
            "admin_panel_path": invariants.admin_panel_path,
            "customer_login_path": invariants.customer_login_path,
        },
        "capabilities": {
            "data": {"provider": "p2hs-cloud", "available": True},
            "auth": {"provider": "p2hs-auth", "magic_link": "magic_link" in invariants.auth_modes},
            "email": {"provider": None, "binding": None, "available": False},
        },
    }


def test_named_admin_path_and_magic_link_reach_every_generated_artifact():
    invariants = extract_runtime_invariants(
        "I would prefer a secure admin url like /be-admin and no index to that "
        "and only accessible with the magic link",
        ProjectRuntimeInvariants(),
    )
    assert invariants.admin_panel_path == "/be-admin"
    assert "magic_link" in invariants.auth_modes

    contract = _contract_dict(invariants)

    contact_files = contact_adapter_files("nuxt_app", runtime_contract=contract)
    magic_adapter = contact_files["server/utils/p2hs-auth-magic.mjs"]
    assert '"/be-admin"' in magic_adapter
    assert "__P2HS_ADMIN_PANEL_PATH__" not in magic_adapter

    sdk_files = app_sdk_files("nuxt_app", runtime_contract=contract)
    client = sdk_files["lib/p2hs-app.js"]
    assert 'DEFAULT_ADMIN_PATH = "/be-admin"' in client
    recipe = json.loads(sdk_files["p2hs/app-recipe.json"])
    assert recipe["recipes"]["staff_dashboard"]["path"] == "/be-admin"

    with tempfile.TemporaryDirectory() as repo_path:
        shell_files = staff_shell_files("nuxt_app", repo_path, runtime_contract=contract)
    assert "pages/be-admin/index.vue" in shell_files
    assert "pages/admin/index.vue" not in shell_files


def test_the_generated_files_pass_the_guard_that_would_catch_a_regression():
    """A file this chain just produced must never trip the very check meant to
    catch a future run hardcoding /admin -- proves the generated output and the
    guard agree, not just that each was individually tested to pass."""
    invariants = extract_runtime_invariants(
        "Put the admin dashboard at /be-admin with magic link sign-in.",
        ProjectRuntimeInvariants(),
    )
    contract = _contract_dict(invariants)

    with tempfile.TemporaryDirectory() as raw:
        root = Path(raw)
        (root / "p2hs").mkdir()
        (root / "p2hs" / "runtime-contract.json").write_text(json.dumps(contract), encoding="utf-8")

        for name, content in contact_adapter_files("html", runtime_contract=contract).items():
            target = root / name
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text(content, encoding="utf-8")
        for name, content in app_sdk_files("html", runtime_contract=contract).items():
            target = root / name
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_text(content, encoding="utf-8")

        # The generated output alone must pass clean.
        validate_backend_repo(raw)

        # A regression -- some other file still hardcoding /admin -- must still be caught.
        bad = root / "js" / "legacy-redirect.js"
        bad.parent.mkdir(parents=True, exist_ok=True)
        bad.write_text("location.replace('/admin');", encoding="utf-8")
        try:
            validate_backend_repo(raw)
        except ValueError as exc:
            assert "hardcoded /admin redirect" in str(exc)
        else:
            raise AssertionError("expected validate_backend_repo to reject the regression")
