"""Verify that the Home marketing corpus still has a truthful Core mapping.

This is intentionally an audit, not an admission mechanism.  The generated
coverage artifact remains the source of truth for page-to-capability rows and
the platform registry remains authoritative for architecture admission.

Use ``--strict`` for the release gate.  Until all architecture and runtime
proof work is complete, strict mode is expected to report the open rows.
"""

from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path

import yaml

from scripts.harvest_marketing_product_coverage import OUT, harvest

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


def build_report() -> dict:
    expected = harvest()
    current = yaml.safe_load(OUT.read_text(encoding="utf-8")) if OUT.is_file() else None
    rows = expected["pages"]
    unresolved = [
        {
            "slug": row["slug"],
            "class": row["class"],
            "architecture_family": row.get("architecture_family"),
            "gaps": row.get("gaps", []),
            "mismatches": row.get("mismatches", []),
        }
        for row in rows
        if row["class"] in {"C4", "C5", "C6"}
        or row.get("starter") in {"missing", "mismatch"}
        or row.get("gaps")
        or row.get("coverage", {}).get("composition") != "covered"
    ]
    return {
        "schema_version": 1,
        "corpus": expected["corpus"],
        "page_count": expected["page_count"],
        "class_counts": dict(Counter(row["class"] for row in rows)),
        "coverage_artifact_current": current == expected,
        "strict_ready": not unresolved and current == expected,
        "unresolved_count": len(unresolved),
        "unresolved": unresolved,
        "bounded_exclusion_count": sum(bool(row.get("mismatches")) for row in rows),
    }


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--strict", action="store_true", help="fail while any buildability row is open")
    parser.add_argument("--json", action="store_true", help="emit the complete report as JSON")
    args = parser.parse_args()

    report = build_report()
    if args.json:
        print(json.dumps(report, indent=2, sort_keys=True))
    else:
        print(
            f"marketing buildability pages={report['page_count']} "
            f"classes={report['class_counts']} "
            f"unresolved={report['unresolved_count']} "
            f"artifact_current={report['coverage_artifact_current']}"
        )
        for row in report["unresolved"]:
            print(
                f"- {row['class']} {row['slug']} "
                f"family={row['architecture_family'] or '-'} "
                f"gaps={','.join(row['gaps']) or '-'} "
                f"mismatches={','.join(row['mismatches']) or '-'}"
            )
    return 0 if (not args.strict or report["strict_ready"]) else 1


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