#!/usr/bin/env python3
"""build_presence — authored presence overlay → validated presence.json.

Reads presence.authored.yaml (the hand-maintained distribution SSOT: artist
profiles + per-release platform links), stamps a DEFAULT provenance on any link
that omits its own (source=file — these were consolidated from the site's hardcoded
components), validates the whole thing against models.Presence, and writes
presence.json. The site can consume that JSON to retire its duplicated link tables;
catalog/eda surfaces can join releases to tracks (.tidal id) and gigs (site slug).

    python3 build_presence.py        # → presence.json
"""
import json
from datetime import date
from pathlib import Path

import yaml

import models as M

HERE = Path(__file__).resolve().parent
SRC = HERE / "presence.authored.yaml"
OUT = HERE / "presence.json"
# where the links were consolidated FROM — the default provenance locator
SITE_COMPONENTS = "Web/www/next/components/parvagues/{MusicSection,AlbumCarousel,Layout,ParVaguesFooter}.js"


def build():
    raw = yaml.safe_load(SRC.read_text())
    as_of = raw.get("as_of") or date.today().isoformat()
    default_prov = M.Provenance(source=M.Source.file, locator=SITE_COMPONENTS,
                                as_of=date.fromisoformat(as_of),
                                note="consolidated from the site's hardcoded link tables")

    def stamp(link: dict) -> dict:
        link.setdefault("prov", default_prov.model_dump(mode="json"))
        return link

    raw["profiles"] = [stamp(p) for p in raw.get("profiles", [])]
    for rel in raw.get("releases", []):
        rel["links"] = [stamp(x) for x in rel.get("links", [])]
        for t in rel.get("tracks", []):
            t["links"] = [stamp(x) for x in t.get("links", [])]

    return M.Presence.model_validate(raw)   # raises on any bad shape


def main():
    p = build()
    OUT.write_text(p.model_dump_json(indent=1, by_alias=True))
    nlinks = len(p.profiles) + sum(len(r.links) + sum(len(t.links) for t in r.tracks)
                                   for r in p.releases)
    plats = sorted({l.platform.value for l in p.profiles})
    print(f"✓ {OUT.name}: {len(p.profiles)} profiles ({', '.join(plats)}), "
          f"{len(p.releases)} releases, {nlinks} links total")


if __name__ == "__main__":
    main()
