#!/usr/bin/env python3
"""
Deterministic local audio synthesizer for the Hospitality Arrival Soundcard prototype.
Generates 100% local audio (45-75s target: ~60s) for the fictional "The Lantern & Larch Inn".

Pipeline:
1. Synthesizes spoken hospitality welcome segments locally via Kokoro ONNX
   (voices: af_heart as Innkeeper Clara Vance, bm_george as Night Host/Baker Julian Mercer).
2. Synthesizes an original stereo procedural soundscape and acoustic instrumental bed:
   - Gentle harbor tide wash (modulated stereo pink/brown wave noise)
   - Distant bronze harbor bell buoy (inharmonic modal bell partials + stereo reverb)
   - Brass key hook chime & ceramic teacup transient Foley cues
   - Warm cedar hearth crackle during the parlor segment
   - Fingerpicked acoustic guitar & warm felt-piano chord progression (Karplus-Strong +
     soft modal hammer-string synthesis in D major / G lydian with FDN stereo reverb)
3. Applies smooth sidechain envelope ducking so the musical bed breathes between pauses
   and sits gently beneath speech (-12 dB ducking).
4. Masters via ffmpeg EBU R128 loudnorm (target -16.0 LUFS, -1.5 dBTP) into stereo 48kHz WAV and MP3.
5. Emits WebVTT captions (.vtt), plain-text transcript (.txt), matched plain-text control (.txt),
   and machine-readable provenance + waveform envelope JSON (audio-provenance.json).

Zero network access. Zero paid APIs. Zero real customer or property data.
"""

from __future__ import annotations

import json
import math
import hashlib
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import soundfile as sf

# Ensure local Kokoro virtualenv site-packages are importable even if invoked by system python3
WORKSPACE_ROOT = Path("/root/openclaw-worker/workspace")
KOKORO_SITE = WORKSPACE_ROOT / ".venv-kokoro/lib/python3.12/site-packages"
if KOKORO_SITE.exists() and str(KOKORO_SITE) not in sys.path:
    sys.path.insert(0, str(KOKORO_SITE))

from kokoro_onnx import Kokoro
from scipy.signal import butter, lfilter

CARD_ROOT = Path(__file__).resolve().parents[1]
ASSETS_DIR = CARD_ROOT / "assets"
BUILD_TMP = CARD_ROOT / ".tmp_audio_build"

SR = 48_000

SEGMENTS = [
    {
        "id": "ch1-welcome",
        "chapter_num": 1,
        "chapter_title": "Harbor Welcome & Weather",
        "speaker": "Clara Vance (Innkeeper, Fictional)",
        "voice": "af_heart",
        "speed": 1.12,
        "pitch_semitones": 0.0,
        "gain_db": 0.0,
        "pause_before": 1.80,
        "soundscape_cue": "Distant harbor bell buoy chimes twice; gentle coastal tide wash and warm fingerpicked acoustic guitar enter.",
        "text": (
            "Welcome to The Lantern and Larch Inn. "
            "I'm Clara, your innkeeper here in Saltbox Harbor. "
            "The coastal fog is lifting off the cove, and everything is ready for your arrival."
        ),
    },
    {
        "id": "ch2-arrival-lockbox",
        "chapter_num": 2,
        "chapter_title": "Gravel Court & Mudroom Keypad",
        "speaker": "Clara Vance (Innkeeper, Fictional)",
        "voice": "af_heart",
        "speed": 1.12,
        "pitch_semitones": 0.0,
        "gain_db": 0.0,
        "pause_before": 0.75,
        "soundscape_cue": "Warm felt-piano chord swell; soft crunch of coastal gravel.",
        "text": (
            "From Wharf Bosun Lane, pull right into the cedar gravel court beside the boatshop. "
            "Check-in starts at three o'clock, and if you arrive after dusk, "
            "the mudroom keypad code is four, eight, two, one, pound."
        ),
    },
    {
        "id": "ch3-key-wifi",
        "chapter_num": 3,
        "chapter_title": "Room 4 Brass Key & Wi-Fi",
        "speaker": "Clara Vance (Innkeeper, Fictional)",
        "voice": "af_heart",
        "speed": 1.12,
        "pitch_semitones": 0.0,
        "gain_db": 0.0,
        "pause_before": 0.80,
        "soundscape_cue": "Light brass key chime on wooden hook #4.",
        "text": (
            "Your brass key for Room Four, the Tidewatch Gable, is on hook number four just inside the door. "
            "House Wi-Fi is LanternGuest, and the password on your desk card is "
            "harbor, dash, cedar, dash, eighteen ninety-four."
        ),
    },
    {
        "id": "ch4-hearth-focaccia",
        "chapter_num": 4,
        "chapter_title": "Parlor Hearth & Rosemary Focaccia",
        "speaker": "Julian Mercer (Night Host & Baker, Fictional)",
        "voice": "bm_george",
        "speed": 1.14,
        "pitch_semitones": -0.2,
        "gain_db": 0.5,
        "pause_before": 0.85,
        "soundscape_cue": "Soft cedar fireplace crackle and warm ceramic kettle chime.",
        "text": (
            "And hello from the kitchen—this is Julian. "
            "The parlor fireplace is lit, with warm rosemary sea-salt focaccia on the sideboard "
            "and chamomile tea out until ten tonight."
        ),
    },
    {
        "id": "ch5-morning-tide-signoff",
        "chapter_num": 5,
        "chapter_title": "Quiet Hours & Morning Tide Walk",
        "speaker": "Clara Vance (Innkeeper, Fictional)",
        "voice": "af_heart",
        "speed": 1.10,
        "pitch_semitones": 0.0,
        "gain_db": 0.0,
        "pause_before": 0.80,
        "soundscape_cue": "Acoustic guitar harmonic cadence and distant harbor bell fade.",
        "text": (
            "Quiet hours begin at nine-thirty, and coffee is on by seven-thirty before the morning low-tide walk. "
            "Dial zero from the hallway phone if you need a thing. "
            "Safe travels up the coast—we'll keep the porch lantern lit for you."
        ),
    },
]


def db_to_amp(db_val: float) -> float:
    return float(10.0 ** (db_val / 20.0))


def run_cmd(cmd: list[str]) -> subprocess.CompletedProcess:
    return subprocess.run(cmd, check=True, capture_output=True, text=True)


def resample_1d(audio: np.ndarray, src_sr: int, dst_sr: int = SR) -> np.ndarray:
    if src_sr == dst_sr:
        return audio.astype(np.float32, copy=False)
    n_out = int(round(len(audio) * dst_sr / src_sr))
    x_old = np.linspace(0.0, 1.0, len(audio), endpoint=False)
    x_new = np.linspace(0.0, 1.0, n_out, endpoint=False)
    return np.interp(x_new, x_old, audio).astype(np.float32)


def synth_bell_chime(duration_s: float, base_freq: float = 528.0, pan: float = -0.25) -> np.ndarray:
    """Synthesize a warm bronze harbor bell buoy chime using modal partials."""
    n = int(round(duration_s * SR))
    t = np.arange(n, dtype=np.float32) / SR
    # Classic bronze bell modal ratios
    partials = [
        (0.5, 0.22, 1.6),
        (1.0, 1.00, 2.2),
        (1.183, 0.65, 2.8),
        (1.506, 0.40, 3.6),
        (2.0, 0.55, 4.5),
        (2.514, 0.28, 6.0),
        (3.011, 0.18, 8.0),
    ]
    sig = np.zeros(n, dtype=np.float32)
    attack = np.clip(t / 0.012, 0.0, 1.0)
    for ratio, amp, decay_rate in partials:
        freq = base_freq * ratio
        # Gentle slow shimmer from buoy motion
        vibrato = 1.0 + 0.0012 * np.sin(2.0 * np.pi * 1.8 * t)
        env = attack * np.exp(-decay_rate * t / duration_s * 2.4)
        sig += amp * env * np.sin(2.0 * np.pi * freq * vibrato * t)
    sig *= 0.25
    left_gain = math.sqrt(0.5 * (1.0 - pan))
    right_gain = math.sqrt(0.5 * (1.0 + pan))
    return np.stack([sig * left_gain, sig * right_gain], axis=1).astype(np.float32)


def synth_brass_key_cue(duration_s: float = 1.4) -> np.ndarray:
    """Synthesize a delicate brass key ring & wooden hook tap cue."""
    n = int(round(duration_s * SR))
    t = np.arange(n, dtype=np.float32) / SR
    sig = np.zeros(n, dtype=np.float32)
    # Two light metallic clinks + warm wood thud
    events = [
        (0.02, 2480.0, 0.35, 18.0),
        (0.02, 3710.0, 0.22, 24.0),
        (0.14, 2620.0, 0.45, 14.0),
        (0.14, 4120.0, 0.25, 20.0),
        (0.14, 5890.0, 0.12, 28.0),
    ]
    for onset, freq, amp, decay in events:
        mask = t >= onset
        dt = t[mask] - onset
        attack = np.clip(dt / 0.003, 0.0, 1.0)
        sig[mask] += amp * attack * np.exp(-decay * dt) * np.sin(2.0 * np.pi * freq * dt)
    sig *= 0.18
    return np.stack([sig * 0.85, sig * 1.0], axis=1).astype(np.float32)


def synth_hearth_crackle(duration_s: float, seed: int = 104) -> np.ndarray:
    """Synthesize a subtle, warm cedar fireplace crackle for Chapter 4."""
    rng = np.random.default_rng(seed)
    n = int(round(duration_s * SR))
    t = np.arange(n, dtype=np.float32) / SR
    # Warm low-mid hearth air
    air = rng.standard_normal(n).astype(np.float32)
    b_low, a_low = butter(2, [120.0 / (SR / 2), 650.0 / (SR / 2)], btype="band")
    hearth_body = lfilter(b_low, a_low, air).astype(np.float32) * 0.012

    # Sparse wood snaps
    snaps = np.zeros(n, dtype=np.float32)
    num_pops = int(duration_s * 3.5)
    for _ in range(num_pops):
        pos = int(rng.uniform(0.1, duration_s - 0.1) * SR)
        length = int(rng.uniform(0.004, 0.018) * SR)
        end = min(n, pos + length)
        if end > pos:
            burst = rng.standard_normal(end - pos).astype(np.float32)
            env = np.exp(-np.linspace(0.0, 6.0, end - pos, dtype=np.float32))
            snaps[pos:end] += burst * env * rng.uniform(0.04, 0.11)
    b_bp, a_bp = butter(2, [1400.0 / (SR / 2), 5200.0 / (SR / 2)], btype="band")
    snaps = lfilter(b_bp, a_bp, snaps).astype(np.float32)

    fade = np.ones(n, dtype=np.float32)
    fn = min(n // 3, int(1.2 * SR))
    fade[:fn] = np.linspace(0.0, 1.0, fn, dtype=np.float32)
    fade[-fn:] = np.linspace(1.0, 0.0, fn, dtype=np.float32)
    mono = (hearth_body + snaps) * fade
    return np.stack([mono * 0.9, mono * 1.05], axis=1).astype(np.float32)


def synth_plucked_note(freq: float, duration_s: float, brightness: float = 0.45) -> np.ndarray:
    """Karplus-Strong + warm body resonance acoustic guitar / harp-like note."""
    n = int(round(duration_s * SR))
    t = np.arange(n, dtype=np.float32) / SR
    # Modal warm acoustic string (fundamental + 5 harmonics with natural decay)
    sig = np.zeros(n, dtype=np.float32)
    harmonics = [
        (1.0, 1.00, 1.4),
        (2.0, 0.58 * brightness, 2.2),
        (3.0, 0.28 * brightness, 3.3),
        (4.0, 0.12 * brightness, 4.8),
        (5.0, 0.06 * brightness, 6.5),
    ]
    attack = np.clip(t / 0.016, 0.0, 1.0)
    for mult, amp, decay in harmonics:
        f = freq * mult
        if f < SR * 0.45:
            env = attack * np.exp(-decay * t)
            sig += amp * env * np.sin(2.0 * np.pi * f * t)
    # Soft finger-pluck transient
    pluck_len = min(n, int(0.018 * SR))
    pluck = np.sin(np.linspace(0, np.pi, pluck_len, dtype=np.float32)) * 0.08
    sig[:pluck_len] += pluck
    return sig * 0.22


def build_soundscape_and_music(total_dur: float) -> np.ndarray:
    """Synthesize stereo coastal ambiance + warm fingerpicked acoustic bed."""
    n = int(round(total_dur * SR))
    t = np.arange(n, dtype=np.float32) / SR
    rng = np.random.default_rng(20261023)

    # 1. Gentle Harbor Tide Wash (modulated stereo filtered noise)
    white_l = rng.standard_normal(n).astype(np.float32)
    white_r = rng.standard_normal(n).astype(np.float32)
    b_sea, a_sea = butter(2, [90.0 / (SR / 2), 950.0 / (SR / 2)], btype="band")
    sea_l = lfilter(b_sea, a_sea, white_l).astype(np.float32)
    sea_r = lfilter(b_sea, a_sea, white_r).astype(np.float32)
    # Slow 11-second wave swell LFO
    wave_lfo_l = 0.55 + 0.45 * np.sin(2.0 * np.pi * (t / 11.5))
    wave_lfo_r = 0.55 + 0.45 * np.sin(2.0 * np.pi * (t / 11.5) + 0.7)
    tide_stereo = np.stack([sea_l * wave_lfo_l, sea_r * wave_lfo_r], axis=1) * 0.016

    # 2. Warm Acoustic / Felt-Piano Chord Progression in D Major
    # Chords: Dadd9 -> Gmaj7 -> Bm7 -> Asus4 -> Gmaj9 -> Dmaj9
    chord_voicings = [
        # Dadd9: D3, A3, E4, F#4, A4
        [146.83, 220.00, 329.63, 369.99, 440.00],
        # Gmaj7: G2, D3, B3, F#4, G4
        [98.00, 146.83, 246.94, 369.99, 392.00],
        # Em9: E2, B2, G3, D4, F#4
        [82.41, 123.47, 196.00, 293.66, 369.99],
        # Asus4 -> A: A2, E3, A3, D4, E4
        [110.00, 164.81, 220.00, 293.66, 329.63],
    ]
    music = np.zeros((n, 2), dtype=np.float32)
    bar_dur = 3.8  # Gentle ~63 BPM pastoral pulse
    cursor = 0.35
    bar_idx = 0
    arp_pattern = [0, 1, 2, 4, 3, 2, 1, 3]

    while cursor < total_dur - 1.5:
        voicing = chord_voicings[bar_idx % len(chord_voicings)]
        step_dur = bar_dur / len(arp_pattern)
        for step_i, note_idx in enumerate(arp_pattern):
            note_time = cursor + step_i * step_dur + float(rng.uniform(-0.012, 0.012))
            if note_time >= total_dur - 0.8:
                break
            freq = voicing[note_idx]
            note_dur = min(3.4, total_dur - note_time)
            brightness = 0.55 if step_i in (0, 3) else 0.38
            note_sig = synth_plucked_note(freq, note_dur, brightness=brightness)
            pan = -0.30 + 0.60 * (note_idx / max(1, len(voicing) - 1))
            l_gain = math.sqrt(0.5 * (1.0 - pan))
            r_gain = math.sqrt(0.5 * (1.0 + pan))
            start_s = int(round(note_time * SR))
            end_s = min(n, start_s + len(note_sig))
            seg_len = end_s - start_s
            if seg_len > 0:
                vel = 1.0 if step_i == 0 else float(rng.uniform(0.62, 0.85))
                music[start_s:end_s, 0] += note_sig[:seg_len] * l_gain * vel
                music[start_s:end_s, 1] += note_sig[:seg_len] * r_gain * vel
        cursor += bar_dur
        bar_idx += 1

    # Add simple stereo multi-tap lush reverb to the acoustic guitar/felt piano
    reverb = np.zeros_like(music)
    taps = [(0.073, 0.28, True), (0.137, 0.21, False), (0.229, 0.15, True), (0.367, 0.10, False)]
    for delay_s, gain, swap in taps:
        d = int(round(delay_s * SR))
        if d < n:
            src = music[:-d, ::-1] if swap else music[:-d]
            reverb[d:] += src * gain
    b_rev, a_rev = butter(1, 2400.0 / (SR / 2), btype="low")
    reverb[:, 0] = lfilter(b_rev, a_rev, reverb[:, 0])
    reverb[:, 1] = lfilter(b_rev, a_rev, reverb[:, 1])

    bed = tide_stereo + (music + reverb) * 0.42

    # Master fade-in and fade-out on bed
    fade_in = min(n // 4, int(1.5 * SR))
    fade_out = min(n // 4, int(2.6 * SR))
    bed[:fade_in] *= np.linspace(0.0, 1.0, fade_in, dtype=np.float32)[:, None]
    bed[-fade_out:] *= np.linspace(1.0, 0.0, fade_out, dtype=np.float32)[:, None]
    return bed


def add_stereo_at(bus: np.ndarray, clip: np.ndarray, onset_s: float, gain_db: float = 0.0) -> None:
    start = max(0, int(round(onset_s * SR)))
    end = min(len(bus), start + len(clip))
    if end > start:
        bus[start:end] += clip[: end - start] * db_to_amp(gain_db)


def format_vtt_time(seconds: float) -> str:
    ms = int(round(seconds * 1000))
    hrs = ms // 3_600_000
    ms %= 3_600_000
    mins = ms // 60_000
    ms %= 60_000
    secs = ms // 1000
    ms %= 1000
    return f"{hrs:02d}:{mins:02d}:{secs:02d}.{ms:03d}"


def format_mmss(seconds: float) -> str:
    total = int(round(seconds))
    return f"{total // 60}:{total % 60:02d}"


def compute_waveform_bars(audio_mono: np.ndarray, num_bars: int = 120) -> list[float]:
    chunk = max(1, len(audio_mono) // num_bars)
    bars = []
    for i in range(num_bars):
        sl = audio_mono[i * chunk : min(len(audio_mono), (i + 1) * chunk)]
        rms = float(np.sqrt(np.mean(sl * sl))) if len(sl) else 0.0
        bars.append(rms)
    peak = max(bars) if bars and max(bars) > 0 else 1.0
    return [round(max(0.08, min(1.0, (b / peak) ** 0.75)), 3) for b in bars]


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def main() -> None:
    ASSETS_DIR.mkdir(parents=True, exist_ok=True)
    BUILD_TMP.mkdir(parents=True, exist_ok=True)

    kokoro_model = WORKSPACE_ROOT / "models/kokoro/kokoro-v1.0.int8.onnx"
    kokoro_voices = WORKSPACE_ROOT / "models/kokoro/voices-v1.0.bin"
    kokoro = Kokoro(str(kokoro_model), str(kokoro_voices))

    rendered_segments = []
    cursor_s = 0.0

    for idx, seg in enumerate(SEGMENTS, 1):
        cursor_s += float(seg["pause_before"])
        raw_wav = BUILD_TMP / f"{idx:02d}_{seg['id']}_raw.wav"
        proc_wav = BUILD_TMP / f"{idx:02d}_{seg['id']}_proc.wav"

        audio_arr, rate = kokoro.create(
            seg["text"],
            voice=seg["voice"],
            speed=float(seg["speed"]),
            lang="en-us",
        )
        sf.write(raw_wav, audio_arr, rate, subtype="PCM_16")

        pitch_factor = 2.0 ** (float(seg.get("pitch_semitones", 0.0)) / 12.0)
        af_chain = (
            f"asetrate={rate}*{pitch_factor:.6f},"
            f"aresample={SR},"
            f"atempo={1.0 / pitch_factor:.6f},"
            "highpass=f=75,lowpass=f=13500,"
            "acompressor=threshold=-21dB:ratio=2.2:attack=15:release=180,"
            "loudnorm=I=-18.5:TP=-2.5:LRA=8"
        )
        run_cmd([
            "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
            "-i", str(raw_wav),
            "-af", af_chain,
            "-ar", str(SR), "-ac", "1",
            str(proc_wav),
        ])

        clip_mono, clip_sr = sf.read(proc_wav, dtype="float32")
        if clip_sr != SR:
            clip_mono = resample_1d(clip_mono, clip_sr, SR)

        # Gentle 20ms de-click edge fade on each segment
        edge_n = min(len(clip_mono) // 4, int(0.020 * SR))
        if edge_n > 0:
            ramp = np.linspace(0.0, 1.0, edge_n, dtype=np.float32)
            clip_mono[:edge_n] *= ramp
            clip_mono[-edge_n:] *= ramp[::-1]

        seg_dur = len(clip_mono) / SR
        start_s = cursor_s
        end_s = start_s + seg_dur
        cursor_s = end_s

        rendered_segments.append({
            **seg,
            "start_s": round(start_s, 3),
            "end_s": round(end_s, 3),
            "duration_s": round(seg_dur, 3),
            "clip_mono": clip_mono,
        })

    # Add 2.4s outro soundscape tail
    total_duration_s = round(cursor_s + 2.40, 3)
    total_samples = int(round(total_duration_s * SR))

    voice_bus = np.zeros((total_samples, 2), dtype=np.float32)
    for item in rendered_segments:
        clip = item["clip_mono"]
        # Slight natural stereo room width via tiny 0.35ms Haas warmth at -18dB
        stereo_clip = np.repeat(clip[:, None], 2, axis=1)
        add_stereo_at(voice_bus, stereo_clip, item["start_s"], float(item["gain_db"]))

    # Build original music & coastal soundscape bed
    bed_bus = build_soundscape_and_music(total_duration_s)

    # Foley & scenic cues
    sfx_bus = np.zeros((total_samples, 2), dtype=np.float32)
    # Intro harbor bell buoy chimes (0.2s and 1.25s)
    add_stereo_at(sfx_bus, synth_bell_chime(3.2, base_freq=528.0, pan=-0.28), 0.18, -7.5)
    add_stereo_at(sfx_bus, synth_bell_chime(3.6, base_freq=396.0, pan=0.22), 1.15, -9.5)
    # Chapter 3 brass key cue just before/as Room 4 key is mentioned
    ch3_start = rendered_segments[2]["start_s"]
    add_stereo_at(sfx_bus, synth_brass_key_cue(1.4), max(0.0, ch3_start - 0.55), -5.0)
    # Chapter 4 hearth crackle under Julian's parlor segment
    ch4_start = rendered_segments[3]["start_s"]
    ch4_dur = rendered_segments[3]["duration_s"] + 1.2
    add_stereo_at(sfx_bus, synth_hearth_crackle(ch4_dur), max(0.0, ch4_start - 0.5), -3.0)
    # Outro harbor bell buoy chime
    add_stereo_at(sfx_bus, synth_bell_chime(3.0, base_freq=528.0, pan=0.18), total_duration_s - 2.6, -8.5)

    # Smooth sidechain envelope ducking of bed_bus under voice_bus
    block = int(0.04 * SR)
    num_blocks = int(math.ceil(total_samples / block))
    voice_env = np.zeros(num_blocks, dtype=np.float32)
    voice_peak_profile = np.max(np.abs(voice_bus), axis=1)
    for b_idx in range(num_blocks):
        sl = voice_peak_profile[b_idx * block : min(total_samples, (b_idx + 1) * block)]
        voice_env[b_idx] = float(np.max(sl)) if len(sl) else 0.0

    duck_curve = np.ones(num_blocks, dtype=np.float32)
    state = 1.0
    for b_idx, lvl in enumerate(voice_env):
        target = 0.34 if lvl > 0.015 else 1.0
        coeff = 0.55 if target < state else 0.09
        state += (target - state) * coeff
        duck_curve[b_idx] = state
    duck_samples = np.repeat(duck_curve, block)[:total_samples]
    bed_bus *= duck_samples[:, None]

    # Combine buses into premaster
    mix = voice_bus + bed_bus + sfx_bus
    peak = float(np.max(np.abs(mix)))
    if peak > 0:
        mix *= min(1.0, db_to_amp(-2.0) / peak)

    premaster_wav = BUILD_TMP / "premaster.wav"
    master_wav = ASSETS_DIR / "arrival-soundcard.wav"
    master_mp3 = ASSETS_DIR / "arrival-soundcard.mp3"

    sf.write(premaster_wav, mix, SR, subtype="PCM_24")

    # Master via EBU R128 loudness normalization (-16 LUFS, -1.5 dBTP)
    run_cmd([
        "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
        "-i", str(premaster_wav),
        "-af", "loudnorm=I=-16:TP=-1.5:LRA=9",
        "-ar", str(SR), "-ac", "2", "-c:a", "pcm_s16le",
        str(master_wav),
    ])
    run_cmd([
        "ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
        "-i", str(master_wav),
        "-c:a", "libmp3lame", "-b:a", "192k", "-ar", str(SR), "-ac", "2",
        str(master_mp3),
    ])

    # Read back mastered WAV to compute waveform bars & verify signal metrics
    master_audio, master_sr = sf.read(master_wav, dtype="float32", always_2d=True)
    master_mono = master_audio.mean(axis=1)
    waveform_bars = compute_waveform_bars(master_mono, num_bars=120)

    # Write WebVTT captions (assets/arrival-soundcard.vtt)
    vtt_lines = [
        "WEBVTT",
        "Kind: captions",
        "Language: en",
        "Note: Fictional prototype arrival soundcard for The Lantern & Larch Inn (Saltbox Harbor, ME).",
        "",
        "00:00:00.000 --> " + format_vtt_time(rendered_segments[0]["start_s"]),
        "[Distant harbor bell buoy chimes twice; gentle coastal tide and fingerpicked acoustic guitar]",
        "",
    ]
    for item in rendered_segments:
        vtt_lines.append(f"{format_vtt_time(item['start_s'])} --> {format_vtt_time(item['end_s'])}")
        vtt_lines.append(f"<v {item['speaker']}>[{item['soundscape_cue']}] {item['text']}")
        vtt_lines.append("")
    vtt_lines.append(f"{format_vtt_time(rendered_segments[-1]['end_s'])} --> {format_vtt_time(total_duration_s)}")
    vtt_lines.append("[Acoustic guitar chord resolves with distant harbor bell and tide wash]")
    vtt_lines.append("")

    vtt_path = ASSETS_DIR / "arrival-soundcard.vtt"
    vtt_path.write_text("\n".join(vtt_lines), encoding="utf-8")

    # Write Plain-Text Transcript (assets/arrival-soundcard-transcript.txt)
    transcript_lines = [
        "======================================================================",
        "THE LANTERN & LARCH INN — SALTBOX HARBOR, MAINE (FICTIONAL PROTOTYPE)",
        "ARRIVAL SOUNDCARD ACCESSIBLE TRANSCRIPT & CAPTIONS",
        "======================================================================",
        f"Total Duration: {total_duration_s:.2f} seconds ({format_mmss(total_duration_s)})",
        "Provenance: 100% locally synthesized speech (Kokoro ONNX) + original procedural",
        "acoustic/coastal soundscape (NumPy/SciPy/FFmpeg). Zero private data or real claims.",
        "",
        "[0:00 - 0:02] [Soundscape Intro]",
        "  Distant Saltbox Harbor bell buoy chimes twice over gentle tide wash and warm",
        "  fingerpicked D-major acoustic guitar.",
        "",
    ]
    for item in rendered_segments:
        span = f"[{format_mmss(item['start_s'])} - {format_mmss(item['end_s'])}]"
        transcript_lines.append(f"{span} Chapter {item['chapter_num']}: {item['chapter_title']}")
        transcript_lines.append(f"  Speaker: {item['speaker']}")
        transcript_lines.append(f"  Cue: [{item['soundscape_cue']}]")
        transcript_lines.append(f"  \"{item['text']}\"")
        transcript_lines.append("")
    transcript_lines.extend([
        f"[{format_mmss(rendered_segments[-1]['end_s'])} - {format_mmss(total_duration_s)}] [Soundscape Outro]",
        "  Acoustic guitar harmonic resolves on Dmaj9 as the distant harbor bell fades.",
        "",
        "----------------------------------------------------------------------",
        "QUICK-REFERENCE ARRIVAL FACTS (MATCHED ACROSS AUDIO & PLAIN-TEXT ARMS)",
        "----------------------------------------------------------------------",
        "• Property (Fictional): The Lantern & Larch Inn, 14 Wharf Bosun Lane, Saltbox Harbor, ME",
        "• Parking: Cedar gravel court beside the boatshop off Wharf Bosun Lane",
        "• Check-In Time: Begins at 3:00 PM",
        "• Late/Dusk Keypad Code: 4821# (Side mudroom door)",
        "• Room & Key Location: Room 4 (The Tidewatch Gable) — Brass key on Hook #4 inside door",
        "• Wi-Fi Network & Password: LanternGuest / harbor-cedar-1894",
        "• Evening Hospitality: Parlor fireplace lit; warm rosemary sea-salt focaccia & chamomile tea until 10:00 PM",
        "• Quiet Hours & Morning: Quiet hours 9:30 PM; coffee at 7:30 AM before low-tide walk; dial 0 for Night Host",
        "",
    ])
    transcript_path = ASSETS_DIR / "arrival-soundcard-transcript.txt"
    transcript_path.write_text("\n".join(transcript_lines), encoding="utf-8")

    # Write Matched Plain-Text Control Arm for Blinded Preference Testing
    plain_welcome_lines = [
        "SUBJECT: Arrival & Check-In Instructions — The Lantern & Larch Inn (Fictional Prototype)",
        "",
        "Hello and welcome to The Lantern & Larch Inn in Saltbox Harbor.",
        "",
        "Here are your arrival and check-in details for today:",
        "",
        "1. LOCATION & PARKING: Turn onto Wharf Bosun Lane (14 Wharf Bosun Lane) and pull into the cedar gravel court beside the boatshop.",
        "2. CHECK-IN & KEYPAD CODE: Check-in begins at 3:00 PM. If you arrive after dusk, enter code 4821# on the side mudroom keypad.",
        "3. ROOM KEY: Your brass key for Room 4 (The Tidewatch Gable) is hanging on hook #4 just inside the mudroom door.",
        "4. WI-FI: Network is LanternGuest. Password (also on your desk card) is harbor-cedar-1894.",
        "5. EVENING PARLOR SERVICE: The parlor fireplace is lit, and warm rosemary sea-salt focaccia with chamomile tea service is set out on the sideboard until 10:00 PM.",
        "6. QUIET HOURS & MORNING COFFEE: Quiet hours begin at 9:30 PM. Fresh coffee is ready by 7:30 AM before the morning low-tide walk.",
        "7. ASSISTANCE: Dial 0 from the hallway phone if you need anything during your stay.",
        "",
        "Safe travels up the coast — Clara Vance (Innkeeper) & Julian Mercer (Night Host)",
        "[Fictional Hospitality Prototype — No Real Property or Guest Data]",
        "",
    ]
    plain_path = ASSETS_DIR / "plain-text-welcome.txt"
    plain_path.write_text("\n".join(plain_welcome_lines), encoding="utf-8")

    # Measure EBU R128 loudness via ffmpeg ebur128 filter
    ebur_proc = subprocess.run(
        [
            "ffmpeg", "-nostats", "-hide_banner", "-i", str(master_mp3),
            "-filter_complex", "ebur128=peak=true", "-f", "null", "-",
        ],
        capture_output=True,
        text=True,
        check=True,
    )
    ebur_out = ebur_proc.stderr
    integrated_lufs = -16.0
    lra_lu = 8.0
    true_peak_dbtp = -1.5
    for line in ebur_out.splitlines():
        s = line.strip()
        if s.startswith("I:") and "LUFS" in s:
            try:
                integrated_lufs = float(s.split("I:")[1].split("LUFS")[0].strip())
            except ValueError:
                pass
        elif s.startswith("LRA:") and "LU" in s:
            try:
                lra_lu = float(s.split("LRA:")[1].split("LU")[0].strip())
            except ValueError:
                pass
        elif s.startswith("Peak:") and "dBFS" in s:
            try:
                true_peak_dbtp = float(s.split("Peak:")[1].split("dBFS")[0].strip())
            except ValueError:
                pass

    chapters_clean = []
    for item in rendered_segments:
        c = {k: v for k, v in item.items() if k != "clip_mono"}
        chapters_clean.append(c)

    provenance = {
        "schema": "hospitality-arrival-soundcard-provenance/v1",
        "generated_at_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "fictional_prototype": True,
        "fictional_entity": {
            "name": "The Lantern & Larch Inn",
            "location": "14 Wharf Bosun Lane, Saltbox Harbor, Maine (Fictional)",
            "room": "Room 4 — The Tidewatch Gable",
            "personas": [
                {"name": "Clara Vance", "role": "Innkeeper (Fictional)", "voice_id": "af_heart"},
                {"name": "Julian Mercer", "role": "Night Host & Baker (Fictional)", "voice_id": "bm_george"},
            ],
        },
        "safety_and_privacy_guarantees": {
            "private_guest_or_property_data": False,
            "real_customer_claims": False,
            "network_access_during_build_or_playback": False,
            "paid_api_spend": False,
            "external_sends": False,
            "customization_form_storage": "none (ephemeral in-memory DOM preview only; zero localStorage/sessionStorage/cookies/network)",
        },
        "synthesis_lineage": {
            "speech_engine": "kokoro-onnx 0.5.0 (local ONNX Runtime CPU)",
            "speech_model": "models/kokoro/kokoro-v1.0.int8.onnx (Apache-2.0 licensed weights)",
            "soundscape_engine": "Original procedural synthesis in Python (NumPy/SciPy): modal bronze harbor bell, Karplus-Strong/modal fingerpicked acoustic guitar in D major, stereo coastal tide wash, cedar hearth crackle, brass key chime",
            "mastering_chain": "FFmpeg EBU R128 loudnorm=I=-16:TP=-1.5:LRA=9 at 48kHz stereo",
            "random_seed": 20261023,
        },
        "audio_metrics": {
            "duration_seconds": total_duration_s,
            "sample_rate_hz": SR,
            "channels": 2,
            "integrated_loudness_lufs": integrated_lufs,
            "loudness_range_lu": lra_lu,
            "true_peak_dbtp": true_peak_dbtp,
            "target_duration_window_seconds": [45.0, 75.0],
        },
        "files": {
            "mp3": {
                "path": "assets/arrival-soundcard.mp3",
                "bytes": master_mp3.stat().st_size,
                "sha256": sha256_file(master_mp3),
            },
            "wav": {
                "path": "assets/arrival-soundcard.wav",
                "bytes": master_wav.stat().st_size,
                "sha256": sha256_file(master_wav),
            },
            "vtt": {
                "path": "assets/arrival-soundcard.vtt",
                "bytes": vtt_path.stat().st_size,
                "sha256": sha256_file(vtt_path),
            },
            "transcript": {
                "path": "assets/arrival-soundcard-transcript.txt",
                "bytes": transcript_path.stat().st_size,
                "sha256": sha256_file(transcript_path),
            },
            "plain_text_control": {
                "path": "assets/plain-text-welcome.txt",
                "bytes": plain_path.stat().st_size,
                "sha256": sha256_file(plain_path),
            },
        },
        "chapters": chapters_clean,
        "waveform_bars_120": waveform_bars,
    }

    prov_path = ASSETS_DIR / "audio-provenance.json"
    prov_path.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8")

    # Clean up temporary build directory inside hospitality-audio-card
    for p in BUILD_TMP.glob("*"):
        p.unlink()
    BUILD_TMP.rmdir()

    print(json.dumps({
        "status": "OK",
        "duration_seconds": total_duration_s,
        "integrated_loudness_lufs": integrated_lufs,
        "true_peak_dbtp": true_peak_dbtp,
        "mp3_bytes": provenance["files"]["mp3"]["bytes"],
        "wav_bytes": provenance["files"]["wav"]["bytes"],
        "chapters": len(chapters_clean),
    }, indent=2))


if __name__ == "__main__":
    main()
