"""PROMPT_ALIGNMENT_02: live first-build conformance proof.

Does not change Fast Lane recipe files, 13A/B2 gold, or documents_ops_08.
"""

import tempfile
from pathlib import Path

import pytest
from src.domain.app_blocks.prompt_alignment_live_02 import (
    LIVE_ARTIFACT,
    LIVE_FIXTURES,
    prove_live_first_build,
    write_live_artifact,
)
from src.domain.app_blocks.vertical_recipes import RECIPE_DIR

ROOT = Path(__file__).resolve().parents[1]


@pytest.fixture(scope="module")
def live_proof():
    raw = tempfile.TemporaryDirectory(prefix="p2hs-pa02-")
    try:
        base = Path(raw.name)
        report = prove_live_first_build(base)
        write_live_artifact(report)
        yield report, base
    finally:
        raw.cleanup()


def test_prompt_alignment_02_live_first_build_conformance(live_proof):
    report, _base = live_proof
    exit_block = report["exit"]
    assert report["documents_ops_08_waited"] is False
    assert report["recipe_files_unchanged"] == sorted(
        path.name for path in RECIPE_DIR.glob("*.yaml")
    )
    assert {cell["fixture_id"] for cell in report["cells"]} >= {
        "student_admissions",
        "legal_intake",
        "construction_punch_list",
        "it_service_desk",
        "content_publishing_approval",
        "student_admissions_negative",
        "quote_configuration_required",
    }
    assert LIVE_ARTIFACT.is_file()
    assert exit_block == {
        "prompt_alignment_live_proven": "yes",
        "discovery_intent_fidelity_proven": "yes",
        "planner_authority_preserved": "yes",
        "codegen_composition_authority_preserved": "yes",
        "generated_private_backend": 0,
        "undeclared_routes": 0,
        "undeclared_tables": 0,
        "undeclared_auth": 0,
        "undeclared_ownership": 0,
        "provider_simulation": 0,
        "vertical_ui_terms_preserved": "yes",
        "canonical_runtime_ids_preserved": "yes",
        "negative_intent_respected": "yes",
        "configuration_required_substituted": "no",
        "unavailable_capability_substituted": "no",
    }


def test_live_apps_keep_vertical_ui_terms_off_canonical_ids(live_proof):
    report, base = live_proof
    by_id = {cell["fixture_id"]: cell for cell in report["cells"]}
    for fixture in LIVE_FIXTURES:
        cell = by_id[fixture.recipe_id]
        for block_id, heading in fixture.ui_terms.items():
            assert cell["ui_terms"][block_id] == heading
            entity_key = cell["runtime_ids"][block_id]
            assert entity_key == fixture.runtime_ids[block_id]
            assert heading != entity_key
            assert heading != block_id
        blob = "\n".join(
            path.read_text(encoding="utf-8")
            for path in (base / fixture.recipe_id / "pages").rglob("*.vue")
        )
        for heading in fixture.ui_terms.values():
            assert heading in blob


def test_negative_intent_removes_recipe_documents_only(live_proof):
    report, _base = live_proof
    positive = next(
        cell for cell in report["cells"] if cell["fixture_id"] == "student_admissions"
    )
    negative = next(
        cell
        for cell in report["cells"]
        if cell["fixture_id"] == "student_admissions_negative"
    )
    assert "documents" in positive["block_ids"]
    assert "documents" not in negative["block_ids"]
    assert "case.management" in negative["block_ids"]
    assert "crm.customer" in negative["block_ids"]
    assert negative["negative_intent_respected"] is True


def test_configuration_required_and_unavailable_are_not_substituted(live_proof):
    report, base = live_proof
    quote = next(
        cell
        for cell in report["cells"]
        if cell["fixture_id"] == "quote_configuration_required"
    )
    assert quote["configuration_required_substituted"] is False
    settings = (
        base / "quote_configuration_required" / "pages" / "admin" / "settings.vue"
    ).read_text(encoding="utf-8")
    assert "Setup required" in settings
    pages = "\n".join(
        path.read_text(encoding="utf-8")
        for path in (base / "student_admissions").rglob("*.vue")
    )
    assert "api.hubapi.com" not in pages
    assert "new Resend" not in pages
    for cell in report["cells"]:
        if cell["fixture_id"] in {item.recipe_id for item in LIVE_FIXTURES}:
            assert cell["unavailable_capability_substituted"] is False


def test_documents_ops_08_is_not_a_live_fixture():
    assert all(fixture.recipe_id != "documents_ops_08" for fixture in LIVE_FIXTURES)
    names = {fixture.recipe_id for fixture in LIVE_FIXTURES}
    assert "shift_handover_notes" not in names


def test_fast_lane_recipe_catalog_files_are_untouched():
    names = sorted(path.name for path in RECIPE_DIR.glob("*.yaml"))
    assert names == [
        "approval_ops_06.yaml",
        "booking_03.yaml",
        "case_ops_02.yaml",
        "catalog.v1.yaml",
        "catalog_04.yaml",
        "documents_ops_08.yaml",
        "marketing_coverage.yaml",
        "support_ops_05.yaml",
        "task_ops_07.yaml",
    ]
    assert ROOT.joinpath("scripts", "phase_13a_corpus.txt").is_file()
