#!/usr/bin/env python3
"""build_catalog — the GENERATED catalog (replaces hand-maintained catalog.yaml).

catalog.yaml had no knowable "valid as of". The catalog is now a downstream
artifact: derived facts from `catalog_view.json` (sounds, gigs, takes, recording
status, A↔C level) ⊕ the authored overlay `catalog.authored.yaml` (license,
inspiration, collab, curated status, notes — each with provenance). Validated
against models.Catalog on emit. Run via `tide.py build catalog` (after catalog_view).

    python3 build_catalog.py
"""
from __future__ import annotations
import json
from pathlib import Path

import yaml

HERE = Path(__file__).parent
CATALOG_VIEW = HERE / "catalog_view.json"
AUTHORED = HERE / "catalog.authored.yaml"
OUT = HERE / "catalog.generated.json"


def build():
    view = json.loads(CATALOG_VIEW.read_text())
    authored = (yaml.safe_load(AUTHORED.read_text()) or {}).get("tracks", {}) or {}
    tracks = []
    for r in view["tracks"]:
        a = authored.get(r["track"], {})
        tracks.append({
            "id": r["track"],
            "title": a.get("title") or r["name"],
            "aka": sorted(set(r["names"]) | set(a.get("aka", []))),
            # derived — do not hand-edit
            "sounds": r["score_sounds"],
            "orbits": r["n_orbits"],
            "gigs": r["gigs"],
            "takes": [t["take"] for t in r["takes"]],
            "recorded": r["recorded"],
            "eda_grounded": r["n_takes_eda"] > 0,
            "ac_level": r["ac"]["level"],
            # authored overlay
            "license": a.get("license"),
            "inspiration": a.get("inspiration", []),
            "collab": a.get("collab", []),
            "status": a.get("status"),
            "notes": a.get("notes"),
            "authored_prov": a.get("prov"),
        })
    return {
        "schema": "catalog v1 (GENERATED — catalog_view ⊕ catalog.authored.yaml; "
                  "do not hand-edit; edit the overlay or the source)",
        "as_of": view["as_of"],
        "n_tracks": len(tracks),
        "n_authored": len(authored),
        "tracks": tracks,
    }


def main():
    out = build()
    from models import Catalog                 # DRY contract: validate before writing
    Catalog.model_validate(out)
    OUT.write_text(json.dumps(out, ensure_ascii=False, indent=1))
    print(f"✓ {OUT}  ({out['n_tracks']} tracks · {out['n_authored']} authored overlays)")


if __name__ == "__main__":
    main()
