#!/usr/bin/env python3
"""Render the listening demo for "Spec: per-event params" and measure each clip.

    python make_demo.py            # from the repository root, on the PR branch; writes demo_out/*.wav and results.json

Every clip is one Spec dict through orb.api.render_spec: nothing here reaches past the public API. The last section asks
the planner for a tuned bell in plain words, to show what params cannot do: they are Spec-only. It is skipped without torch.
"""
from __future__ import annotations

import json
import math
import sys
from pathlib import Path

import numpy as np

ROOT = Path.cwd()
sys.path.insert(0, str(ROOT / "src"))
from orb.api import render_spec, save_wav  # noqa: E402

SR = 48000
OUT = ROOT / "out" / "demo"
OUT.mkdir(parents=True, exist_ok=True)
N = {"C4": 261.63, "D4": 293.66, "F4": 349.23, "F#4": 369.99, "A4": 440.0, "C5": 523.25, "E5": 659.26, "G5": 783.99, "C6": 1046.5, "E6": 1318.5, "G6": 1567.98}


def ev(role, t, dur, seed=0, gain=-6.0, pan=0.0, **params):
    e = {"role": role, "t": t, "dur": dur, "gain_db": gain, "pan": pan, "seed": seed}
    if params:
        e["params"] = params
    return e


def spec(seconds, *events):
    return {"duration": seconds, "texture": "none", "mood": "calm", "events": list(events)}


def peak_hz(a, lo, hi, start=0.3, length=1.5):
    x = a.mean(axis=1)[int(start * SR): int((start + length) * SR)]
    x = x * np.hanning(len(x)); sp = np.abs(np.fft.rfft(x, 1 << 20)); fr = np.fft.rfftfreq(1 << 20, 1 / SR)
    k = (fr > lo) & (fr < hi)
    return float(fr[k][np.argmax(sp[k])])


def cents(f, ref):
    return 1200 * math.log2(f / ref)


def fall_s(a, db=40.0):
    e = np.abs(a).max(axis=1); hop = SR // 20; b = e[: len(e) // hop * hop].reshape(-1, hop).max(axis=1)
    w = np.where(b < b.max() * 10 ** (-db / 20))[0]
    return float(w[0] * hop / SR) if len(w) else None


def centroid(a, seconds=0.15):
    x = a.mean(axis=1)[: int(seconds * SR)]; sp = np.abs(np.fft.rfft(x * np.hanning(len(x)))); fr = np.fft.rfftfreq(len(x), 1 / SR)
    return float((fr * sp).sum() / sp.sum())


def one(role, seed=0, dur=5.0, **params):
    return render_spec(spec(dur, ev(role, 0.0, dur, seed, **params)))


CLIPS = []


def clip(cid, group, title, setting, sp, measured):
    save_wav(render_spec(sp), OUT / f"{cid}.wav")
    CLIPS.append({"id": cid, "group": group, "title": title, "setting": setting, "measured": measured, "seconds": sp["duration"], "spec": sp})
    print(f"{cid:28} {measured}")


# ---- church bell: pitch -------------------------------------------------------------------------------------------
seeds = (0, 2, 4)
cast = [peak_hz(one("church_bell", s), 500, 1000) for s in seeds]
clip("bell-01-as-cast", "Church bell: pitch", "Three bells, as cast (no params)", "seeds 0, 2, 4",
     spec(10.0, *[ev("church_bell", 0.3 + 3 * i, 9.5 - 3 * i, s) for i, s in enumerate(seeds)]),
     "the seed picks each bell: nominals " + ", ".join(f"{c:.0f} Hz" for c in cast))
notes = ("D4", "F4", "A4")
off = [cents(peak_hz(one("church_bell", s, f0=N[n]), 1.9 * N[n], 2.1 * N[n]), 2 * N[n]) for s, n in zip(seeds, notes)]
clip("bell-02-tuned", "Church bell: pitch", "The same three bells on D4, F4, A4", '"params": {"f0": 293.66} and so on',
     spec(10.0, *[ev("church_bell", 0.3 + 3 * i, 9.5 - 3 * i, s, f0=N[n]) for i, (s, n) in enumerate(zip(seeds, notes))]),
     "nominal against 2 x f0: " + ", ".join(f"{o:+.2f}" for o in off) + " cents")
clip("bell-03-chord-minor", "Church bell: pitch", "D minor, all three together", "f0 = D4, F4, A4",
     spec(8.0, *[ev("church_bell", 0.2, 7.6, s, f0=N[n]) for s, n in zip(seeds, notes)]), "a minor chord suits the church bell's minor third")
# ---- church bell: timbre ------------------------------------------------------------------------------------------
maj = ("D4", "F#4", "A4")
clip("bell-04-major-on-minor-bells", "Church bell: timbre", "D major on church bells (tierce 0.6)", "f0 = D4, F#4, A4",
     spec(8.0, *[ev("church_bell", 0.2, 7.6, s, f0=N[n]) for s, n in zip(seeds, maj)]), "each bell's own minor third sits against the major chord")
clip("bell-05-major-on-major-bells", "Church bell: timbre", "D major on major-third bells", '"tierce": 0.63',
     spec(8.0, *[ev("church_bell", 0.2, 7.6, s, f0=N[n], tierce=0.63) for s, n in zip(seeds, maj)]), "the third partial moves from 0.60 to 0.63 of the nominal")
for label, b in (("none", 0.0), ("as-cast", 0.0012), ("heavy", 0.006)):
    clip(f"bell-06-beat-{label}", "Church bell: timbre", f"Beating: {label.replace('-', ' ')}", f'"beat": {b}', spec(9.0, ev("church_bell", 0.2, 8.6, 0, f0=N["A4"], beat=b)),
         "doublets closed: one line per partial" if b == 0 else f"each partial's pair up to {b * 100:.2f}% apart")
# ---- church bell: length ------------------------------------------------------------------------------------------
for r, dur in ((0.35, 5.0), (1.0, 9.0), (2.5, 16.0)):
    f = fall_s(one("church_bell", 0, 24.0, f0=N["A4"], ring=r))
    clip(f"bell-07-ring-{str(r).replace('.', '_')}", "Church bell: length", f"Ring x {r:g}", f'"ring": {r:g}', spec(dur, ev("church_bell", 0.2, dur - 0.3, 0, f0=N["A4"], ring=r)), f"{f:.1f} s to fall 40 dB")
# ---- church bell: strike ------------------------------------------------------------------------------------------
for label, h in (("felt", 0.05), ("as-cast", 0.5), ("hard", 1.0)):
    a = one("church_bell", 0, 5.0, f0=N["A4"], hardness=h)
    clip(f"bell-08-strike-{label}", "Church bell: strike", f"Clapper: {label.replace('-', ' ')}", f'"hardness": {h:g}', spec(6.0, ev("church_bell", 0.2, 5.6, 0, f0=N["A4"], hardness=h)),
         f"spectral centre of the first 150 ms: {centroid(a):.0f} Hz")
steps = [(0.3 + 2.4 * i, -24 + 6 * i, 0.1 + 0.2 * i) for i in range(5)]
clip("bell-09-toll-crescendo", "Church bell: strike", "A toll that grows, as five events", "gain_db -24 to 0, hardness 0.1 to 0.9",
     spec(16.0, *[ev("church_bell", t, 15.8 - t, 0, g, f0=N["D4"], hardness=h, ring=1.4) for t, g, h in steps]), "one event per strike: a single tolling event cannot change strike by strike")
# ---- the synth roles ----------------------------------------------------------------------------------------------
clip("synth-01-bell-as-shipped", "Synth roles", "bell, as shipped", "no params", spec(3.0, ev("bell", 0.2, 2.6)), f"{peak_hz(one('bell', 0, 2.5), 800, 960):.1f} Hz whatever the seed")
arp = ("C5", "E5", "G5", "C6")
offs = [cents(peak_hz(one("bell", 0, 2.5, f0=N[n], t60=2.0), 0.95 * N[n], 1.05 * N[n]), N[n]) for n in arp]
clip("synth-02-bell-arpeggio", "Synth roles", "bell on C5, E5, G5, C6", '"f0": 523.25 …, "t60": 2.0',
     spec(6.0, *[ev("bell", 0.2 + 0.7 * i, 5.6 - 0.7 * i, 0, f0=N[n], t60=2.0) for i, n in enumerate(arp)]), "within " + f"{max(abs(o) for o in offs):.2f} cents of each note")
clip("synth-03-ui-pop-as-shipped", "Synth roles", "ui_pop three times, as shipped", "no params", spec(2.0, *[ev("ui_pop", 0.2 + 0.4 * i, 0.3, 0) for i in range(3)]), "all near 880 Hz")
clip("synth-04-ui-pop-tuned", "Synth roles", "ui_pop on C6, E6, G6", '"f0": 1046.5 …', spec(2.0, *[ev("ui_pop", 0.2 + 0.4 * i, 0.3, 0, f0=N[n]) for i, n in enumerate(("C6", "E6", "G6"))]), "a three-note confirmation in key")
for label, f in (("low", 45.0), ("as-shipped", None), ("high", 120.0)):
    clip(f"synth-05-impact-{label}", "Synth roles", f"impact, {label.replace('-', ' ')}", "no params" if f is None else f'"f0": {f:g}', spec(2.0, ev("impact", 0.2, 1.2, **({} if f is None else {"f0": f}))), "body at 70 Hz" if f is None else f"body at {f:g} Hz")
clip("synth-06-sub-drop-as-shipped", "Synth roles", "sub_drop, as shipped", "no params", spec(2.5, ev("sub_drop", 0.2, 2.0)), "110 Hz down to 35 Hz")
clip("synth-07-sub-drop-wide", "Synth roles", "sub_drop from 220 Hz to 40 Hz", '"f0": 220, "f_end": 40', spec(2.5, ev("sub_drop", 0.2, 2.0, f0=220.0, f_end=40.0)), "an octave more travel")

# ---- what plain words cannot reach --------------------------------------------------------------------------------
planned = []
try:
    from orb.api import load_planner, plan, spec_to_dict
    tok, model = load_planner(None)
    for i, prompt in enumerate(("a church bell ringing on the note D", "three church bells tolling a D minor chord", "a soft low bell, then a hard high bell")):
        sp = spec_to_dict(plan(prompt, tok, model)); save_wav(render_spec(sp), OUT / f"typed-{i + 1}.wav")
        planned.append({"id": f"typed-{i + 1}", "prompt": prompt, "spec": sp, "has_params": any("params" in e for e in sp["events"])})
        print(f"typed-{i + 1}: {prompt} -> " + ", ".join(f'{e["role"]}#{e["seed"]}' for e in sp["events"]))
except ImportError as err:
    print("planner section skipped:", err)

(OUT / "results.json").write_text(json.dumps({"clips": CLIPS, "typed": planned}, indent=1))
print(len(CLIPS), "clips,", len(planned), "typed prompts ->", OUT)
