#!/usr/bin/env python3
"""Register freshly cut third-party sample kits in the rights ledger, blocked by default.

A kit cut from somebody else's stems is not releasable per-track until a human says so
(`reference_sample_rights_audit`). Left alone, a new `fred_*` bank would land in the
ledger as `unknown` the next time `rights_audit.py --init` ran — which does block, but
blocks with no reason attached, so whoever reads it later has to re-derive where the
audio came from. Recording the provenance at the moment of cutting is the whole point
of `feedback_metadata_provenance`: value, source, locator, date.

    python3 register_fred_rights.py <fred_kits.json> [--source "..."]
"""
from __future__ import annotations

import argparse
import json
from datetime import date
from pathlib import Path

HERE = Path(__file__).resolve().parent
LEDGER = HERE / "rights_ledger.json"


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("cuts_json", type=Path)
    ap.add_argument("--source", default="Fred again.. producer stem pack (fan dropbox)")
    ap.add_argument("--status", default="third_party",
                    choices=["third_party", "unknown", "cleared", "original"])
    a = ap.parse_args()

    cuts = json.loads(a.cuts_json.read_text())
    led = json.loads(LEDGER.read_text())
    banks = led.setdefault("banks", {})

    counts: dict[str, int] = {}
    tracks: dict[str, set] = {}
    for c in cuts:
        counts[c["kit"]] = counts.get(c["kit"], 0) + 1
        tracks.setdefault(c["kit"], set()).add(c["track"])

    added = updated = 0
    for kit, n in sorted(counts.items()):
        note = f"cut by engine.stempack from {a.source} — source track(s): " \
               f"{', '.join(sorted(tracks[kit]))}"
        if kit in banks and banks[kit].get("status") not in (None, "unknown"):
            updated += 1                       # never overwrite a human verdict
            banks[kit]["files"] = n
            continue
        banks[kit] = {"status": a.status, "origin": "local", "files": n,
                      "note": note, "decided": date.today().isoformat()}
        added += 1

    LEDGER.write_text(json.dumps(led, indent=1) + "\n")
    print(f"{added} bank(s) registered as {a.status}; {updated} already had a verdict and were left alone")
    print(f"ledger: {LEDGER}")
    return 0


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