"""Rebuild the independent Studio Check timing reference and audio in a given directory.

Requires espeakng-loader==0.2.4 and ffmpeg on PATH. Run from a fresh Python process:
    python3 generate_studio.py /tmp/studio-check
    python3 convert.py /tmp/studio-check/studio-check-reference.json --format vtt
"""
import argparse
import array
import ctypes as C
import json
import re
import subprocess
import tempfile
import wave
from pathlib import Path

from espeakng_loader import get_data_path, get_library_path


LINES = [
    ("Maya", "en-us+f3", 158, "Is the studio booked for Tuesday?"),
    ("Leo", "en+m2", 150, "Yes. We have the room until noon."),
    ("Maya", "en-us+f3", 158, "Great. I'll bring the blue microphone."),
    ("Leo", "en+m2", 150, "I'll bring the spare cable."),
]
METHOD = (
    "Original scripted synthetic dialogue. Word starts come from eSpeak NG synthesis events. "
    "Cue ends use the last PCM sample above 64 on the int16 scale plus up to 20 ms of available audio. "
    "Non-final word ends use the next word onset, so they may include a pause. All times are seconds from "
    "the start of the WAV, rounded to the nearest millisecond. Speaker names identify the scripted voices. "
    "No recognition output is used to set the reference."
)


class EventId(C.Union):
    _fields_ = [("number", C.c_int), ("name", C.c_char_p), ("string", C.c_char * 8)]


class Event(C.Structure):
    _fields_ = [
        ("type", C.c_int), ("unique_identifier", C.c_uint), ("text_position", C.c_int),
        ("length", C.c_int), ("audio_position", C.c_int), ("sample", C.c_int),
        ("user_data", C.c_void_p), ("id", EventId),
    ]


def build(output):
    engine = C.CDLL(get_library_path())
    engine.espeak_Initialize.argtypes = [C.c_int, C.c_int, C.c_char_p, C.c_int]
    engine.espeak_Synth.argtypes = [
        C.c_void_p, C.c_size_t, C.c_uint, C.c_int, C.c_uint, C.c_uint, C.c_void_p, C.c_void_p
    ]
    engine.espeak_Info.argtypes = [C.POINTER(C.c_char_p)]
    engine.espeak_Info.restype = C.c_char_p
    data_directory = Path(get_data_path()).parent
    sample_rate = engine.espeak_Initialize(2, 0, str(data_directory).encode(), 1)
    if sample_rate <= 0:
        raise RuntimeError("Could not initialize eSpeak NG in synchronous output mode")
    callback_type = C.CFUNCTYPE(C.c_int, C.POINTER(C.c_short), C.c_int, C.POINTER(Event))

    @callback_type
    def record(buffer, count, events):
        if count:
            pcm.frombytes(C.string_at(buffer, count * 2))
        index = 0
        while events[index].type:
            event = events[index]
            if event.type == 1:  # espeakEVENT_WORD, positions are 1-indexed
                markers.append((event.text_position - 1, event.audio_position))
            index += 1
        return 0

    engine.espeak_SetSynthCallback.argtypes = [callback_type]
    engine.espeak_SetSynthCallback(record)
    # Pin the synthesizer noise generator to the seed used by the published recording.
    engine.espeak_ng_SetRandSeed(1795516089)
    silence = array.array("h", [0])
    audio = silence * round(sample_rate * 0.20)
    turns, words, voices = [], [], {}
    for number, (speaker, voice, speed, text) in enumerate(LINES, 1):
        pcm = array.array("h")
        markers = []
        if engine.espeak_SetVoiceByName(voice.encode()) or engine.espeak_SetParameter(1, speed, 0):
            raise RuntimeError(f"Could not set voice {voice} at {speed} wpm")
        encoded = text.encode("ascii")
        if engine.espeak_Synth(encoded, len(encoded) + 1, 0, 1, 0, 1, None, None) or engine.espeak_Synchronize():
            raise RuntimeError("eSpeak failed to synthesize the line")
        tokens = list(re.finditer(r"\S+", text))
        markers = [(pos, ms) for pos, ms in markers if pos < len(text)]
        if [pos for pos, ms in markers] != [word.start() for word in tokens]:
            raise ValueError(f"Word markers do not match the source script in turn {number}")
        last_active = next(i for i in range(len(pcm)-1, -1, -1) if abs(pcm[i]) > 64)
        retained = min(len(pcm), last_active + 1 + int(sample_rate * 0.02))
        offset = len(audio)
        onsets = [round(offset / sample_rate + ms / 1000, 3) for pos, ms in markers]
        end = round((offset + retained) / sample_rate, 3)
        turns.append(dict(speaker=speaker, start=onsets[0], end=end, text=text))
        for word, start, stop in zip(tokens, onsets, onsets[1:] + [end]):
            words.append(dict(speaker=speaker, start=start, end=stop, word=word.group()))
        voices[speaker] = f"{voice} ({speed} words per minute)"
        audio.extend(pcm[:retained])
        audio.extend(silence * round(sample_rate * (0.30 if number == len(LINES) else 0.48)))

    output.mkdir(parents=True, exist_ok=True)
    recording = output / "studio-check.wav"
    with tempfile.TemporaryDirectory() as tmp:
        master = str(Path(tmp) / "master.wav")
        with wave.open(master, "wb") as f:
            f.setparams((1, 2, sample_rate, len(audio), "NONE", "not compressed"))
            f.writeframes(audio.tobytes())
        subprocess.run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-i", master,
                        "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", str(recording)], check=True)
    with wave.open(str(recording), "rb") as f:
        duration = f.getnframes() / f.getframerate()
    reference = {
        "title": "Studio check", "language": "en", "duration": round(duration, 6),
        "sampleRate": 16000, "speakerCount": 2, "method": METHOD,
        "source": {"engine": engine.espeak_Info(None).decode(), "package": "espeakng-loader 0.2.4",
                   "voices": voices, "turnGapSeconds": 0.48},
        "turns": turns, "words": words,
    }
    (output / "studio-check-reference.json").write_text(json.dumps(reference, indent=2) + "\n", encoding="utf-8")
    (output / "studio-check.txt").write_text("".join(f"{t['speaker']}: {t['text']}\n" for t in turns), encoding="utf-8")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("output", type=Path)
    build(parser.parse_args().output)
