"""Consolidation lock for Fast Lane batches 05–07.

Every live recipe in support_ops_05, approval_ops_06, and task_ops_07 must
resolve through the same planner path: match_recipe_for_intent ->
select_capabilities recipe union. Phrases must not steal across families.
"""

from pathlib import Path

from src.domain.app_blocks.compiler import compile_install_plan
from src.domain.app_blocks.execution import assert_install_plan_installable
from src.domain.app_blocks.planner import ProductIntent, select_capabilities
from src.domain.app_blocks.vertical_recipes import (
    load_recipe_catalogs,
    load_recipes,
    match_recipe_for_intent,
)
from src.domain.projects.discovery_schemas import (
    Actor,
    AuthenticationSpec,
    DiscoverySpec,
    Entity,
    ProductDefinition,
    TenancySpec,
    Workflow,
)

CHECKPOINT_BATCHES = ("support_ops_05", "approval_ops_06", "task_ops_07")
RECEIPT_KEYS = (
    "fast_lane_batch",
    "status",
    "lane",
    "capabilities_consumed",
    "vertical_recipes_added",
    "new_semantics_invented",
    "booking_catalog_selectable",
)
RECIPE_DIR = Path(__file__).resolve().parents[1] / "src/domain/app_blocks/recipes"


def _checkpoint_recipes():
    recipes = []
    for catalog in load_recipe_catalogs():
        if catalog.batch in CHECKPOINT_BATCHES:
            assert catalog.ready_for_fast_lane_composition is True
            recipes.extend(catalog.recipes)
    return recipes


def test_checkpoint_batches_are_live_including_booking_and_catalog():
    live = {catalog.batch: catalog.ready_for_fast_lane_composition for catalog in load_recipe_catalogs()}
    for batch in CHECKPOINT_BATCHES:
        assert live[batch] is True
    assert live["booking_03"] is True
    assert live["catalog_04"] is True
    live_ids = {recipe.id for recipe in load_recipes(composition_ready_only=True)}
    assert "clinic_booking" in live_ids
    assert "course_catalog" in live_ids


def test_checkpoint_recipes_resolve_through_the_live_planner_union():
    for recipe in _checkpoint_recipes():
        intent = ProductIntent(
            purpose=recipe.intent_phrases[0],
            first_build_goal=recipe.intent_phrases[0],
            source_prompt=recipe.intent_phrases[0],
            staff_review=True,
        )
        matched = match_recipe_for_intent(intent)
        assert matched is not None, recipe.id
        assert matched.id == recipe.id
        selected = {block_id for _cap, block_id, _reason in select_capabilities(intent)}
        assert set(recipe.required_app_blocks) <= selected
        plan = compile_install_plan(
            DiscoverySpec(
                product=ProductDefinition(
                    purpose=recipe.intent_phrases[0],
                    first_build_goal=f"Ship {recipe.name}",
                ),
                archetypes=["operations"],
                actors=[Actor(id="staff", name="Staff")],
                workflows=[Workflow(id="run", name="Run", description=recipe.intent_phrases[0])],
                entities=[Entity(id="record", name="Record", description="Record")],
                tenancy=TenancySpec(model="single_workspace"),
                authentication=AuthenticationSpec(required=False),
            ),
            source_prompt=recipe.intent_phrases[0],
        )
        assert_install_plan_installable(plan)


def test_all_recipe_phrases_are_unique_and_non_nested():
    owned: dict[str, str] = {}
    batch_by_recipe: dict[str, str] = {}
    collisions = []
    nested = []
    for catalog in load_recipe_catalogs():
        for recipe in catalog.recipes:
            batch_by_recipe[recipe.id] = catalog.batch
            for phrase in recipe.intent_phrases:
                if phrase in owned and owned[phrase] != recipe.id:
                    collisions.append((phrase, owned[phrase], recipe.id))
                owned[phrase] = recipe.id
    phrases = sorted(owned)
    for left in phrases:
        for right in phrases:
            if left == right or owned[left] == owned[right]:
                continue
            if "marketing_coverage" in {
                batch_by_recipe[owned[left]],
                batch_by_recipe[owned[right]],
            }:
                continue
            if left in right:
                nested.append((left, owned[left], right, owned[right]))
    assert collisions == []
    assert nested == []


def test_checkpoint_receipts_are_consistent():
    for batch in CHECKPOINT_BATCHES:
        text = (RECIPE_DIR / f"{batch}.receipt.txt").read_text(encoding="utf-8")
        assert f"fast_lane_batch={batch}" in text
        for key in RECEIPT_KEYS:
            assert f"{key}=" in text, f"{batch} missing {key}"
        assert "new_semantics_invented=no" in text
        assert "booking_catalog_selectable=no" in text
        assert "status=complete" in text
        assert "lane=fast_lane" in text
