#!/usr/bin/env python3
"""sections_from_brief.py — the sections file is PROPOSED from the brief, approved by the operator.

Film #2's sections.json was hand-authored from a transcript that had missed a fifth of
the song: it labelled 79–109 s "break" when both children sang through it, and the
plan cut a sung verse to B-roll. He authored a correct file from a wrong input (film3
item 7, 2026-09-02). The brief — lines placed by the three ears against the sheet — is
the input that is right, so the sections come from it:

  * contiguous runs of placed lines by sheet section tag ("Hook - Both" -> "Hook") are
    the sections; each runs from its first line's onset to the next section's first
    onset (the last to the song's end); an instrumental head of INTRO_MIN_S or more is
    its own "Intro" section in the opening world;
  * worlds come from the pack's SECTION_WORLDS="Hook=jasmine-garden-morning,Verse 1=banyan-swing,…"
    when a section is named there, else round-robin over the DRAWN styles whose
    performer matches the section's voice (a `both` tag takes a two-performer world);
  * the file records the brief's sha; `--check <authored>` refuses an authored file that
    was made against a different brief, and NAMES (never refuses) a label that reads as a
    break over placed lines — labels are editorial, the sha is what pins correctness.

Usage:
  sections_from_brief.py --brief build/vocal-brief.json --styles-drawn build/styles-drawn.json
                         --song-seconds N --out build/sections-proposed.json
                         [--worlds "Hook=id,Verse 1=id"] [--pronouns "he|she"] [--check build/sections.json]
"""
from __future__ import annotations

import argparse
import json
import os as _os
import re
import sys as _sys

_sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))
import raplib  # noqa: E402

INTRO_MIN_S = 4.0          # a wordless head this long is a section of its own (line_windows' INTRO_MIN)
SUNG_IN_BREAK_MAX_S = 3.0  # an authored "break" over more placed singing than this is named (a note)
BOUNDARY_WARN_S = 2.0      # an authored boundary this far from the proposal's is named
BREAK_WORDS = re.compile(r"\b(break|instrumental|intro|outro|interlude|wordless|b-roll)\b", re.I)


def tag_base(tag: str) -> str:
    """'Hook - Both, two small children singing together' -> 'Hook'."""
    base = re.split(r"\s+-\s+|,", (tag or "").strip(), maxsplit=1)[0].strip()
    return base or "Section"


def performer_of(who: str, pronouns: str) -> str:
    """The brief's voice (both/male/female/lead) -> the pack's performer (a/b/both)."""
    if who in ("both", "duet"):
        return "both"
    if who in ("a", "b"):          # a letter-tagged sheet names the performer outright
        return who
    prons = [p.strip() for p in (pronouns or "he|she").split("|")]
    for idx, pr in enumerate(prons[:2]):
        gender = "female" if pr == "she" else "male" if pr == "he" else None
        if gender and gender == who:
            return "ab"[idx]
    return "a"


def runs(lines: list[dict]) -> list[dict]:
    """Contiguous runs of placed lines by section tag, in song order."""
    out: list[dict] = []
    for ln in sorted(lines, key=lambda l: float(l.get("start") or 0)):
        base = tag_base(ln.get("tag") or "")
        if out and out[-1]["tag"] == base:
            r = out[-1]
            r["end"] = max(r["end"], float(ln.get("end") or ln.get("start") or 0))
            r["who"].append(ln.get("who") or "lead")
            r["n"] += 1
        else:
            out.append({"tag": base, "start": float(ln.get("start") or 0),
                        "end": float(ln.get("end") or ln.get("start") or 0),
                        "who": [ln.get("who") or "lead"], "n": 1})
    for r in out:
        votes = set(r["who"])
        # a run sung by more than one voice — a bridge traded line by line — is a both
        # section: two mouths on screen, not one performer's world for the other's lines
        if ("both" in votes or "duet" in votes) or ({"male", "female"} <= votes) or ({"a", "b"} <= votes):
            r["who"] = "both"
        else:
            r["who"] = max(votes, key=r["who"].count)
    return out


def propose(brief: dict, drawn: list[dict], worlds: dict, pronouns: str, song_len: float) -> list[dict]:
    lines = brief.get("lines") or []
    rs = runs(lines)
    if not rs:
        return []
    cursor: dict[str, int] = {}
    used: list[str] = []

    def world_for(r: dict) -> str:
        if r["tag"] in worlds:
            used.append(worlds[r["tag"]])
            return worlds[r["tag"]]
        perf = performer_of(r["who"], pronouns)
        cands = [s for s in drawn if (s.get("performer") or "a") == perf] or drawn
        if not cands:
            raise SystemExit("sections_from_brief: no drawn styles to assign — run the styles stage first")
        # a world no section has yet, so a bridge does not land in the hook's world and
        # read as the hook; only when every candidate is taken does the round-robin repeat
        fresh = [s for s in cands if s["id"] not in used]
        pool = fresh or cands
        pick = pool[cursor.get(perf, 0) % len(pool)]
        cursor[perf] = cursor.get(perf, 0) + 1
        used.append(pick["id"])
        return pick["id"]

    out: list[dict] = []
    first = rs[0]["start"]
    if first >= INTRO_MIN_S:
        out.append({"styleId": world_for(rs[0]), "start": 0.0, "end": round(first, 3),
                    "label": "Intro — instrumental (the opening world, or B-roll)", "performer": "none"})
    for i, r in enumerate(rs):
        start = r["start"] if out else 0.0
        end = rs[i + 1]["start"] if i + 1 < len(rs) else song_len
        out.append({"styleId": world_for(r), "start": round(start, 3), "end": round(end, 3),
                    "label": f"{r['tag']} — {r['who']} ({r['n']} line{'s' if r['n'] != 1 else ''})",
                    "performer": performer_of(r["who"], pronouns)})
    return out


def check(authored: dict, proposal: list[dict], lines: list[dict], brief_sha: str) -> tuple[list[str], list[str]]:
    """(problems, warnings) for an authored sections file against the brief."""
    problems, warnings = [], []
    if authored.get("briefSha") and authored["briefSha"] != brief_sha:
        problems.append(f"the sections file was authored against a different brief (sha {authored['briefSha'][:12]}, "
                        f"the brief is {brief_sha[:12]}) — re-propose, or edit and re-run")
    secs = authored.get("sections") if isinstance(authored, dict) else authored
    for s in secs or []:
        label = str(s.get("label") or "")
        if not BREAK_WORDS.search(label):
            continue
        a, b = float(s.get("start") or 0), float(s.get("end") or 0)
        sung = 0.0
        n = 0
        for ln in lines:
            lo, hi = max(a, float(ln.get("start") or 0)), min(b, float(ln.get("end") or ln.get("start") or 0))
            if hi > lo:
                sung += hi - lo
                n += 1
        if sung > SUNG_IN_BREAK_MAX_S:
            # A NOTE, NOT A REFUSAL. make_plan reads sections as styleId spans only — the
            # label never had a mechanical effect — and film #2's approved file says
            # "Wordless intro" over four sung hook lines and "Final hook + outro" over the
            # closing hook; refusing on prose would have killed the operator's next
            # re-plan of a film he had just approved (advisor, 2026-09-02). The stale
            # briefSha below is the one thing that pins correctness.
            warnings.append(f"{a:.1f}-{b:.1f}s is labelled {label!r} but the brief places {n} line(s), "
                            f"{sung:.1f}s of singing, inside it — the label reads as a break; the sheet says sung")
    starts = [float(p["start"]) for p in proposal]
    for s in secs or []:
        a = float(s.get("start") or 0)
        if starts and min(abs(a - x) for x in starts) > BOUNDARY_WARN_S:
            near = min(starts, key=lambda x: abs(x - a))
            warnings.append(f"a section starts at {a:.1f}s; the brief's nearest boundary is {near:.1f}s")
    return problems, warnings


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--brief", required=True)
    ap.add_argument("--styles-drawn", required=True)
    ap.add_argument("--song-seconds", type=float, required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--worlds", default="", help='SECTION_WORLDS: "Hook=id,Verse 1=id"')
    ap.add_argument("--pronouns", default="he|she")
    ap.add_argument("--check", default="", help="an authored sections file to judge against the brief")
    a = ap.parse_args()
    brief = raplib.read_json(a.brief) or {}
    drawn = (raplib.read_json(a.styles_drawn) or {}).get("styles") or []
    worlds = {}
    for part in [p for p in a.worlds.split(",") if p.strip()]:
        k, _, v = part.partition("=")
        if k.strip() and v.strip():
            worlds[k.strip()] = v.strip()
    sha = raplib.sha256_file(a.brief)
    proposal = propose(brief, drawn, worlds, a.pronouns, a.song_seconds)
    raplib.write_json_atomic(a.out, {"schemaVersion": 1, "briefSha": sha, "sections": proposal,
                                     "_proposed": "from the brief's placed lines by sheet section tag; edit, "
                                                  "then set SECTIONS to this file (or leave unset to take it as is)"},
                             inputs={"brief": a.brief})
    print(f"sections_from_brief: {len(proposal)} section(s) proposed -> {a.out}", file=_sys.stderr)
    for s in proposal:
        print(f"  {s['start']:7.2f}-{s['end']:7.2f}  {s['styleId']:24s}  {s['label']}", file=_sys.stderr)
    if a.check and _os.path.isfile(a.check):
        authored = raplib.read_json(a.check) or {}
        problems, warnings = check(authored, proposal, brief.get("lines") or [], sha)
        for w in warnings:
            print(f"sections_from_brief: note — {w}", file=_sys.stderr)
        if problems:
            print(f"sections_from_brief: REFUSED {a.check} — {len(problems)} disagreement(s) with the brief:", file=_sys.stderr)
            for p in problems:
                print(f"  * {p}", file=_sys.stderr)
            return 4
    return 0


if __name__ == "__main__":
    _sys.exit(main())
