# SPDX-License-Identifier: Apache-2.0
"""Synthesize a short, original TAP/CLAP repeating cue without recordings."""

from __future__ import annotations

import math
import random
import struct
import wave
from pathlib import Path

HERE = Path(__file__).resolve().parent
OUTPUT = HERE / "tap-clap-pattern.wav"
RATE = 16_000
RANDOM = random.Random(2026)
SEQUENCE = ("TAP", "CLAP") * 3


def cue(name: str) -> list[float]:
    """Make one clearly distinct synthetic percussive cue."""
    duration = 0.11 if name == "TAP" else 0.22
    samples: list[float] = []
    for index in range(round(RATE * duration)):
        time = index / RATE
        if name == "TAP":
            value = math.sin(2 * math.pi * 520 * time) * math.exp(-45 * time)
        else:
            noise = RANDOM.uniform(-1.0, 1.0)
            pulse = math.exp(-18 * time) + 0.40 * math.exp(-45 * abs(time - 0.07))
            value = noise * pulse * 0.40
        samples.append(value)
    return samples


def main() -> None:
    """Write six alternating cues with pauses as mono PCM WAV."""
    data: list[float] = []
    for name in SEQUENCE:
        data.extend(cue(name))
        data.extend([0.0] * round(RATE * 0.40))
    pcm = b"".join(
        struct.pack("<h", max(-32767, min(32767, round(value * 26000))))
        for value in data
    )
    with wave.open(str(OUTPUT), "wb") as file:
        file.setnchannels(1)
        file.setsampwidth(2)
        file.setframerate(RATE)
        file.writeframes(pcm)
    print(f"WROTE {OUTPUT.name}: {len(data) / RATE:.2f} s, 16 kHz mono PCM")


if __name__ == "__main__":
    main()
