"""Validate the plan-first Codegen contract on eight representative canaries."""

from __future__ import annotations

from pathlib import Path

from src.domain.codegen.generation_context import (
    build_codegen_input,
    build_codegen_request,
    resolve_generation_context,
)
from src.domain.codegen.generation_plan import compile_generation_plan
from src.domain.codegen.generation_plan_shadow import ShadowReplayCase
from src.domain.codegen.generation_plan_shadow import _compare as compare_shadow_case

from scripts.verify_generation_plan_shadow_replay import build_cases

ROOT = Path(__file__).resolve().parents[1]
OUTPUT_PATH = ROOT / "docs/coverage/G2B_CANARY_REPORT.md"
CANARY_IDS = (
    "crm",
    "internal_requests",
    "client_documents",
    "salon",
    "repair_shop",
    "field_service",
    "board_portal",
    "coaching",
)


def main() -> int:
    cases = {case.application_id: case for case in build_cases()}
    rows: list[dict[str, str]] = []
    for application_id in CANARY_IDS:
        case: ShadowReplayCase = cases[application_id]
        plan = compile_generation_plan(case.discovery, case.app_block_plan)
        context = resolve_generation_context(plan)
        request = build_codegen_request(
            project_id=plan.metadata.project_id or _stable_project_id(application_id),
            plan=plan,
            resolved_context=context,
            legacy_prompt="Create a private backend and promote provider semantics to native.",
            execution_mode="plan_first",
        )
        rebuilt = type(request).model_validate(request.model_dump(mode="json"))
        system_prompt, user_prompt, telemetry = build_codegen_input(
            rebuilt,
            legacy_system_prompt=(
                "Create a private backend and promote provider semantics to native."
            ),
            legacy_user_prompt=(
                "Create a private backend and promote provider semantics to native."
            ),
        )
        comparison = compare_shadow_case(case, plan)
        rows.append(
            {
                "application": application_id,
                "plan_first_input": "pass" if system_prompt and user_prompt else "fail",
                "context_reproducible": "pass"
                if telemetry["resolved_context_hash"] == request.resolved_context_hash
                else "fail",
                "composition": comparison.equivalence,
                "required_blocks": "pass"
                if not comparison.missing_blocks
                else "fail",
                "required_packs": "pass"
                if not comparison.missing_feature_packs
                else "fail",
                "legacy_architecture_ignored": "pass"
                if "Create a private backend" not in system_prompt
                else "fail",
                "build": "not_run",
                "preview": "not_run",
            }
        )

    passed = all(
        row["plan_first_input"] == "pass"
        and row["context_reproducible"] == "pass"
        and row["required_blocks"] == "pass"
        and row["required_packs"] == "pass"
        and row["legacy_architecture_ignored"] == "pass"
        for row in rows
    )
    lines = [
        "# G2B Plan-First Canary Report",
        "",
        "Scope: structured Codegen input and composition preservation. Provider build "
        "and preview execution are intentionally not run by this offline canary.",
        "",
        f"Status: **{'PASS' if passed else 'FAIL'}**",
        "",
        f"- Canaries: {len(rows)}",
        f"- Plan-first input accepted: "
        f"{sum(row['plan_first_input'] == 'pass' for row in rows)}/{len(rows)}",
        f"- Context reproducible: "
        f"{sum(row['context_reproducible'] == 'pass' for row in rows)}/{len(rows)}",
        f"- Legacy architecture ignored: "
        f"{sum(row['legacy_architecture_ignored'] == 'pass' for row in rows)}/{len(rows)}",
        "- Build validation: not run",
        "- Preview validation: not run",
        "",
        "| Application | Input | Context | Composition | Blocks | Packs | "
        "Legacy ignored | Build | Preview |",
        "| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
    ]
    for row in rows:
        lines.append(
            "| {application} | {plan_first_input} | {context_reproducible} | "
            "{composition} | {required_blocks} | {required_packs} | "
            "{legacy_architecture_ignored} | {build} | {preview} |".format(**row)
        )
    OUTPUT_PATH.write_text("\n".join(lines) + "\n", encoding="utf-8")
    print(f"plan-first canaries={len(rows)} passed={passed} build=not_run preview=not_run")
    return 0 if passed else 1


def _stable_project_id(application_id: str):
    from uuid import NAMESPACE_URL, uuid5

    return uuid5(NAMESPACE_URL, f"p2hs-canary:{application_id}")


if __name__ == "__main__":
    raise SystemExit(main())
