#!/usr/bin/env python3
"""Builds the STT-01 / STT-11 ground-truth files from script.txt and checks that every seeded fact, action item,
trap and entity is actually spoken in the script (build fails otherwise). Re-run after any script edit.
Outputs (same folder): reference_transcript.txt (speaker-labelled), reference_plain.txt (WER reference),
answer_key.json, turns.json, MANIFEST.sha256"""
import hashlib, json, re, sys
from pathlib import Path
D = Path(__file__).resolve().parent
SPEAKERS = {"MAYA": "Maya Okafor", "DANIEL": "Daniel Brenner", "PRIYA": "Priya Raman", "TOMAS": "Tomas Herrera"}
turns, section = [], None
for ln in (D / "script.txt").read_text().splitlines():
    if ln.startswith("## "): section = ln[3:].strip(); continue
    if not ln.strip() or ln.startswith("#"): continue
    spk, text = ln.split("|", 1)
    assert spk in SPEAKERS, spk
    turns.append(dict(turn=len(turns) + 1, speaker=spk, name=SPEAKERS[spk], section=section, text=text.strip()))
full = "\n".join(t["text"] for t in turns)
def where(q):
    hits = [t["turn"] for t in turns if q.lower() in t["text"].lower()]
    if not hits: sys.exit(f"NOT SPOKEN in script: {q!r}")
    return hits

FACTS = [  # 12 seeded facts (STT-11): id, statement, accepted forms, evidence phrases that must be spoken
 ("F01", "Launch date moved from November 3 to Tuesday, November 17, 2026", ["November 17", "Nov 17", "17 November"], ["move the launch from November 3rd to Tuesday, November 17th"]),
 ("F02", "Retail price is $79 (not $89), with no discounts below $79 before the end of March", ["$79", "79 dollars"], ["The retail price for Beacon 2 is seventy-nine dollars", "no discounts below seventy-nine before the end of March"]),
 ("F03", "First production run is 4,800 units (down from the planned 6,000)", ["4,800", "4800", "forty-eight hundred"], ["The first production run is four thousand eight hundred units, not six thousand"]),
 ("F04", "Manufacturer is Kestrel Components in Penang", ["Kestrel"], ["Kestrel Components in Penang"]),
 ("F05", "Battery is a 2,600 mAh cell; Portland riders get about 11 hours in flashing mode", ["2,600", "2600"], ["twenty-six hundred milliamp-hour", "around eleven hours on the flashing mode"]),
 ("F06", "Brake light can stay on after the bike stops on firmware 1.4.2; fixed in 1.4.3", ["1.4.2", "1.4.3"], ["firmware version one point four point two", "It's in firmware version one point four point three"]),
 ("F07", "Pre-orders stand at 1,312 (speaker first said 1,321, then corrected)", ["1,312", "1312"], ["one thousand three hundred and twelve pre-orders"]),
 ("F08", "Total launch marketing budget is $18,500", ["$18,500", "18,500", "18.5"], ["eighteen thousand five hundred dollars"]),
 ("F09", "Northgate Outfitters will carry Beacon 2 in 42 stores from launch day (up from 30)", ["42"], ["in forty-two stores from launch day"]),
 ("F10", "Return rate on the previous model was 3.7%", ["3.7"], ["three point seven percent"]),
 ("F11", "Freight from Penang rose from $2.10 to $2.65 per unit", ["2.65", "$2.65"], ["two dollars and ten cents per unit", "two dollars and sixty-five cents per unit"]),
 ("F12", "Beta: 64 riders in Lisbon and Portland; 51 have sent feedback", ["64"], ["sixty-four riders, split between Lisbon and Portland", "fifty-one of them"]),
]
ACTIONS = [  # 8 action items (STT-11): counts only if owner AND deadline are right
 ("A01", "DANIEL", "Ship firmware 1.4.3 to all 64 beta testers", "2026-10-21", "Wednesday, October 21", ["ship one point four point three to all sixty-four beta testers by Wednesday, October 21st"]),
 ("A02", "TOMAS", "Confirm the production slot and 4,800 units with Kestrel in writing", "2026-10-16", "Friday, October 16", ["confirm the production slot and the forty-eight hundred units with Kestrel by Friday, October 16th"]),
 ("A03", "TOMAS", "Get two freight quotes: all-sea vs air for pre-order units + sea for the rest", "2026-10-19", "Monday, October 19", ["both freight quotes by Monday, October 19th"]),
 ("A04", "PRIYA", "Send the revised launch email draft (new date, $79) to Maya", "2026-10-20", "Tuesday, October 20", ["send the revised draft to Maya by Tuesday, October 20th"]),
 ("A05", "MAYA", "Update the pricing page and product page to $79", "2026-10-23", "Friday, October 23", ["update the pricing page and the product page to seventy-nine dollars by Friday, October 23rd"]),
 ("A06", "PRIYA", "Brief Elena Varga (Northgate buyer): price, date, photos, one-page staff sheet incl. carbon-handlebar answer", "2026-10-27", "Tuesday, October 27", ["brief Elena Varga at Northgate by Tuesday, October 27th"]),
 ("A07", "DANIEL", "Write the UN 38.3 battery test summary and share with Tomas and Priya", "2026-10-30", "Friday, October 30", ["UN thirty-eight point three test summary and share it with Tomas and Priya by Friday, October 30th"]),
 ("A08", "MAYA", "Schedule the go/no-go meeting for Tuesday, November 10 (send the invite today)", "2026-10-12", "today (Monday, October 12); meeting on Tuesday, November 10", ["schedule a go/no-go meeting for Tuesday, November 10th", "I'll send the invite today"]),
]
MINOR = [  # small asks: not counted for recall, NOT hallucinations if a tool lists them
 ("M01", "DANIEL", "Send Priya the exact carbon-handlebar wording today", ["I can send you the exact wording for that today"]),
 ("M02", "DANIEL", "Send Tomas the UN 38.3 certificate today", ["I can send you the certificate itself today"]),
 ("M03", "DANIEL", "Add a carbon-handlebar line to the FAQ", ["I'll add a line to the FAQ"]),
 ("M04", "DANIEL", "Give Kestrel the final firmware file at least five working days before the run", ["at least five working days before the run"]),
 ("M05", "PRIYA", "Tell press about the new embargo date and include a firmware-update note", ["I'll include a short note when we send the date change"]),
 ("M06", "PRIYA", "Make the FAQ say there is no app at launch", ["make sure the FAQ says that clearly"]),
 ("M07", "MAYA", "Review the launch email the same day it arrives", ["I'll review it the same day"]),
 ("M08", "PRIYA", "Share trade-show notes in the channel", ["I'll share the full notes in the channel"]),
]
DECISIONS = [
 ("D01", "Launch moves to Tuesday, November 17 (from November 3)", ["Then it's decided. The launch date is now Tuesday, November 17th"]),
 ("D02", "Price $79, not $89; no discounts below $79 before end of March", ["So here's the decision. The retail price for Beacon 2 is seventy-nine dollars"]),
 ("D03", "First production run 4,800 units, not 6,000", ["Let's make that the decision"]),
 ("D04", "No TikTok influencer campaign for the launch; revisit in January with a smaller test", ["Let's not do the TikTok campaign for the launch"]),
 ("D05", "Firmware 1.4.3 contains only the brake-light fix; then it is locked", ["One fix, one week of testing, then we lock it"]),
 ("D06", "Freight decision deferred to next week's sync (NOT decided today)", ["freight gets decided at next week's sync"]),
]
TRAPS = [  # things a summary must NOT state (each instance = hallucination or error)
 ("T01", "Lists the TikTok influencer campaign ($5,000) as an action item or as approved", ["a budget of about five thousand dollars"]),
 ("T02", "States 1,321 pre-orders (misspoken, corrected to 1,312)", ["one thousand three hundred and twenty-one. Sorry"]),
 ("T03", "States the price is $89 or still undecided", ["We're not going with eighty-nine"]),
 ("T04", "States the launch is November 3", ["November 3rd is realistic anymore"]),
 ("T05", "States the run is 6,000 units", ["The original plan was a first run of six thousand units"]),
 ("T06", "Says Beacon 2 is discounted / sold at $49 (only leftover Beacon 1 stock, website only)", ["sell them at forty-nine dollars"]),
 ("T07", "States Northgate's opening order as confirmed 600 units (it is a soft, unconfirmed number)", ["that's not confirmed"]),
 ("T08", "States a freight decision was made (sea or air)", ["we decide on freight at next week's sync"]),
 ("T09", "Gives any air-freight price (none was stated)", ["I don't have a firm air quote yet"]),
 ("T10", "Attributes the competitor's $85 price to Beacon 2", ["It's eighty-five dollars"]),
 ("T11", "Says there will be a companion app at launch", ["Not at launch"]),
]
ENTITIES = [  # 40 named entities / numbers (spoken form -> accepted written forms)
 ("Beacon 2", ["Beacon 2", "Beacon two"]), ("Beacon 1", ["Beacon 1", "Beacon one"]), ("Kestrel Components", ["Kestrel Components"]),
 ("Penang", ["Penang"]), ("Northgate Outfitters", ["Northgate Outfitters", "Northgate"]), ("Elena Varga", ["Elena Varga"]),
 ("Lisbon", ["Lisbon"]), ("Portland", ["Portland"]), ("TikTok", ["TikTok", "Tik Tok"]), ("USB-C", ["USB-C", "USB C"]),
 ("IPX6", ["IPX6", "IP X6", "IPX 6"]), ("UN 38.3", ["UN 38.3", "UN38.3"]), ("1.4.2", ["1.4.2"]), ("1.4.3", ["1.4.3"]),
 ("64 riders", ["64"]), ("51 forms", ["51"]), ("2,600 mAh", ["2,600", "2600"]), ("11 hours", ["11 hours", "eleven hours"]),
 ("9 riders", ["9 riders", "nine riders"]), ("35 mm", ["35"]), ("8.6 out of 10", ["8.6"]), ("4,800 units", ["4,800", "4800"]),
 ("6,000 units", ["6,000", "6000"]), ("3.7%", ["3.7"]), ("1,312", ["1,312", "1312"]), ("$2.10", ["2.10"]), ("$2.65", ["2.65"]),
 ("26%", ["26%", "26 percent"]), ("November 3", ["November 3"]), ("November 17", ["November 17"]), ("$79", ["79"]),
 ("$89", ["89"]), ("$18,500", ["18,500", "18.5"]), ("31,000 subscribers", ["31,000", "31000"]), ("$5,000", ["5,000", "5000"]),
 ("42 stores", ["42"]), ("September 29", ["September 29"]), ("730 units", ["730"]), ("$49", ["49"]), ("140 tickets", ["140"]),
]
SPOKEN = {  # spoken form in the script, for the existence check
 "Beacon 2": "Beacon 2", "Beacon 1": "Beacon 1", "Kestrel Components": "Kestrel Components", "Penang": "Penang", "Northgate Outfitters": "Northgate Outfitters",
 "Elena Varga": "Elena Varga", "Lisbon": "Lisbon", "Portland": "Portland", "TikTok": "TikTok", "USB-C": "USB-C", "IPX6": "IPX6",
 "UN 38.3": "UN thirty-eight point three", "1.4.2": "one point four point two", "1.4.3": "one point four point three", "64 riders": "sixty-four",
 "51 forms": "fifty-one", "2,600 mAh": "twenty-six hundred milliamp-hour", "11 hours": "eleven hours", "9 riders": "Nine riders", "35 mm": "thirty-five millimeters",
 "8.6 out of 10": "eight point six out of ten", "4,800 units": "four thousand eight hundred", "6,000 units": "six thousand units", "3.7%": "three point seven percent",
 "1,312": "one thousand three hundred and twelve", "$2.10": "two dollars and ten cents", "$2.65": "two dollars and sixty-five cents", "26%": "twenty-six percent",
 "November 3": "November 3rd", "November 17": "November 17th", "$79": "seventy-nine dollars", "$89": "eighty-nine dollars", "$18,500": "eighteen thousand five hundred dollars",
 "31,000 subscribers": "thirty-one thousand", "$5,000": "five thousand dollars", "42 stores": "forty-two stores", "September 29": "September 29th",
 "730 units": "Seven hundred and thirty units", "$49": "forty-nine dollars", "140 tickets": "a hundred and forty tickets",
}
assert len(FACTS) == 12 and len(ACTIONS) == 8 and len(ENTITIES) == 40, (len(FACTS), len(ACTIONS), len(ENTITIES))
key = dict(task="STT-01 (also STT-11 script #1)", version="0.1", built_from="script.txt", fictional=True,
           meeting=dict(title="Beacon 2 weekly launch sync", company="Lumen Cycles (fictional)", in_story_date="2026-10-12 (Monday)"),
           speakers=[dict(code=k, display_name=v) for k, v in SPEAKERS.items()],
           seeded_facts=[dict(id=i, statement=s, accept=acc, turns=sorted({x for q in ev for x in where(q)})) for i, s, acc, ev in FACTS],
           action_items=[dict(id=i, owner=SPEAKERS[o], owner_code=o, action=a, deadline=d, deadline_spoken=ds, turns=sorted({x for q in ev for x in where(q)})) for i, o, a, d, ds, ev in ACTIONS],
           minor_commitments=[dict(id=i, owner=SPEAKERS[o], action=a, turns=sorted({x for q in ev for x in where(q)})) for i, o, a, ev in MINOR],
           decisions=[dict(id=i, decision=s, turns=sorted({x for q in ev for x in where(q)})) for i, s, ev in DECISIONS],
           traps=[dict(id=i, must_not=s, turns=sorted({x for q in ev for x in where(q)})) for i, s, ev in TRAPS],
           entities=[dict(entity=e, accept=acc, spoken=SPOKEN[e], turns=where(SPOKEN[e])) for e, acc in ENTITIES],
           scoring=dict(action_item_rule="counts only if owner AND deadline are right; partial credit logged separately (lab/benchmarks/transcription.md STT-11)",
                        minor_commitments_rule="not counted toward recall; a tool listing them is not penalised",
                        hallucination_rule="any statement not supported by reference_transcript.txt, incl. every trap; two raters, third resolves",
                        spec_note="STT-01 text says a 9-item action reference list; STT-11 says 8 action items per script. This script uses 8 committed items + 1 retracted item (T01). Lab lead to align the spec text."))
(D / "answer_key.json").write_text(json.dumps(key, indent=1, ensure_ascii=False))
(D / "turns.json").write_text(json.dumps(turns, indent=1, ensure_ascii=False))
(D / "reference_transcript.txt").write_text("\n".join(f"[{t['turn']:03d}] {t['name']}: {t['text']}" for t in turns) + "\n")
(D / "reference_plain.txt").write_text(" ".join(t["text"] for t in turns) + "\n")
words = sum(len(t["text"].split()) for t in turns)
files = ["script.txt", "answer_key.json", "turns.json", "reference_transcript.txt", "reference_plain.txt"]
(D / "MANIFEST.sha256").write_text("".join(f"{hashlib.sha256((D / f).read_bytes()).hexdigest()}  {f}\n" for f in files))
per = {s: sum(len(t['text'].split()) for t in turns if t['speaker'] == s) for s in SPEAKERS}
print(f"turns={len(turns)} words={words} per_speaker={per} facts=12 actions=8 entities=40 traps={len(TRAPS)} -> OK")
