#!/usr/bin/env python3
from __future__ import annotations
import argparse, json, re
from collections import Counter
from pathlib import Path

FAMILIES = {
    "F1_POLYSEMY_UNDERSPECIFICATION",
    "F2_CAUSAL_ALTERNATIVES",
    "F3_DESIGN_UNDER_CONSTRAINTS",
    "F4_STRUCTURAL_INTERPRETATION",
    "F5_MULTI_SOLUTION_REASONING",
}


def fail(msg: str) -> None:
    raise SystemExit(f"TASK_REGISTRY_INVALID: {msg}")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("registry", type=Path)
    args = ap.parse_args()
    data = json.loads(args.registry.read_text(encoding="utf-8"))
    tasks = data.get("tasks", [])
    if data.get("status") != "PLANNING_ONLY_NEVER_CONFIRMATORY":
        fail("status must be PLANNING_ONLY_NEVER_CONFIRMATORY")
    if len(tasks) < 12:
        fail("fewer than 12 planning tasks")
    ids = [t.get("id") for t in tasks]
    if len(ids) != len(set(ids)):
        fail("duplicate task ids")
    prompts = [" ".join(str(t.get("prompt", "")).lower().split()) for t in tasks]
    if len(prompts) != len(set(prompts)):
        fail("duplicate normalized prompts")
    fam = Counter(t.get("family") for t in tasks)
    unknown = set(fam) - FAMILIES
    if unknown:
        fail(f"unknown families: {sorted(unknown)}")
    for f in FAMILIES:
        if fam[f] < 2:
            fail(f"family {f} has fewer than 2 tasks")
    for t in tasks:
        tid = t.get("id", "")
        if not re.fullmatch(r"PLN_F[1-5]_\d{2}", tid):
            fail(f"bad task id: {tid}")
        if len(t.get("prompt", "").strip()) < 80:
            fail(f"prompt too short: {tid}")
        seeds = t.get("seed_categories_non_exhaustive", [])
        if len(seeds) < 4:
            fail(f"too few non-exhaustive seed categories: {tid}")
        if not t.get("adjudication_focus") or not t.get("relevance_rule"):
            fail(f"missing adjudication/relevance rule: {tid}")
    print(json.dumps({
        "status": "OK",
        "n_tasks": len(tasks),
        "family_counts": dict(sorted(fam.items())),
        "planning_only": True
    }, ensure_ascii=False))

if __name__ == "__main__":
    main()
