#!/usr/bin/env python3
"""pick_styles.py — draw N distinct MV styles from the register, without the
model's help.

"Pick two at random" is a request language models are famously bad at: they
gravitate to the first entries and repeat the same pair across runs. The source
skill tried to fix that with prose ("you must draw from all 8, do not always use
the first two, redraw if you drew the same pair twice"). This does it properly:
a persisted SHUFFLE BAG, seeded per project, drawn without replacement and
refilled only when empty — the same de-patterning already used for B-roll order
in the music-video assembler.

Deterministic: same slug + same bag state => same draw, so a re-run of the
pipeline never silently changes the film's look. `--redraw` advances the bag
deliberately.

Usage:
  pick_styles.py --styles <styles.json> --state <build/style-bag.json>
                 [--slug <slug>] [--count 2] [--redraw] [--only id,id]
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import random
import sys


def die(msg: str) -> None:
    print(f"pick_styles: {msg}", file=sys.stderr)
    raise SystemExit(2)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--styles", required=True)
    ap.add_argument("--state", required=True)
    ap.add_argument("--slug", default="")
    ap.add_argument("--count", type=int, default=2)
    ap.add_argument("--redraw", action="store_true",
                    help="discard the current draw and take the next one from the bag")
    ap.add_argument("--only", default="",
                    help="comma-separated style ids to restrict the bag to (pack allow-list)")
    args = ap.parse_args()

    if not os.path.isfile(args.styles):
        die(f"style register not found: {args.styles}")
    register = json.load(open(args.styles, encoding="utf-8"))
    styles = {s["id"]: s for s in register.get("styles", [])}
    if not styles:
        die(f"no styles in {args.styles}")

    allow = [s.strip() for s in args.only.split(",") if s.strip()]
    if allow:
        unknown = [a for a in allow if a not in styles]
        if unknown:
            die(f"unknown style id(s) in --only: {', '.join(unknown)}. "
                f"Known: {', '.join(sorted(styles))}")
        pool_ids = allow
    else:
        pool_ids = sorted(styles)

    if args.count > len(pool_ids):
        die(f"--count {args.count} exceeds the {len(pool_ids)} available styles")

    state = {}
    if os.path.isfile(args.state):
        try:
            state = json.load(open(args.state, encoding="utf-8"))
        except json.JSONDecodeError:
            state = {}

    # Reuse the existing draw unless asked to redraw — a re-run must not change
    # the film's look behind the operator's back.
    if state.get("draw") and not args.redraw and set(state["draw"]) <= set(pool_ids):
        drawn = state["draw"]
    else:
        bag = [i for i in state.get("bag", []) if i in pool_ids]
        seed = args.slug or os.path.basename(os.path.dirname(os.path.abspath(args.state)))
        rng = random.Random(hashlib.sha256(
            f"{seed}:{state.get('generation', 0)}".encode()).hexdigest())
        drawn = []
        while len(drawn) < args.count:
            if not bag:
                bag = list(pool_ids)
                rng.shuffle(bag)
                state["generation"] = state.get("generation", 0) + 1
            nxt = bag.pop(0)
            if nxt not in drawn:
                drawn.append(nxt)
        state["bag"] = bag
        state["draw"] = drawn

    os.makedirs(os.path.dirname(os.path.abspath(args.state)), exist_ok=True)
    with open(args.state, "w", encoding="utf-8") as fh:
        json.dump(state, fh, indent=2)
        fh.write("\n")

    print(json.dumps({"styles": [styles[i] for i in drawn]}, indent=2))
    print(f"pick_styles: drew {', '.join(drawn)}  "
          f"(bag has {len(state.get('bag', []))} left; --redraw for another pair)",
          file=sys.stderr)


if __name__ == "__main__":
    main()
