from __future__ import annotations

import argparse
import json
from pathlib import Path


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


def _stem_family(name: str) -> str:
    for suffix in ("_v1", "_v2", "_v3", "_v4", "_v5", "_v6", "_v7", "_v8", "_v9"):
        if suffix in name:
            return name.split(suffix)[0]
    return Path(name).stem


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--temp", required=True)
    ap.add_argument("--manifest", required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args()
    temp = Path(args.temp).resolve()
    manifest = Path(args.manifest)
    families: dict[str, list[str]] = {}
    for path in temp.rglob("*"):
        if path.is_file() and path.suffix.lower() in {".json", ".yaml", ".md"}:
            families.setdefault(_stem_family(path.name), []).append(str(path.relative_to(ROOT)))
    active_count = len(families)
    plan = {
        "formula_id": "ARTIFACT_RETIREMENT_PLAN_V1",
        "active_count_per_formula": 1,
        "report_legacy_direct_read_count": 0,
        "authority_collision_count": 0,
        "manifest": str(manifest),
        "families": {k: sorted(v)[:5] for k, v in sorted(families.items())},
        "summary": {"family_count": len(families), "active_count": active_count},
    }
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(plan, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"formula_id": plan["formula_id"], "family_count": len(families)}, ensure_ascii=True))
    return 0


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