#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Generate an original quiet 8-count WAV with complete silent score."""

from __future__ import annotations

import math
import struct
import wave
from pathlib import Path

OUT = Path(__file__).resolve().parent / "audio/folded-pulse.wav"
RATE = 16000
BEAT_SECONDS = 0.4
SCORE = (1, 0, 1, 1, 0, 1, 0, 1)


def sample_at(index: int) -> int:
    beat_length = int(RATE * BEAT_SECONDS)
    beat = index // beat_length
    phase = (index % beat_length) / RATE
    if not SCORE[beat] or phase >= 0.10:
        return 0
    envelope = (1 - phase / 0.10) ** 2
    value = envelope * (0.11 * math.sin(2 * math.pi * 196 * phase)
                        + 0.025 * math.sin(2 * math.pi * 392 * phase))
    return round(value * 32767)


def main() -> None:
    count = int(RATE * BEAT_SECONDS) * len(SCORE)
    samples = [sample_at(i) for i in range(count)]
    OUT.parent.mkdir(parents=True, exist_ok=True)
    with wave.open(str(OUT), "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(RATE)
        wav.writeframes(struct.pack(f"<{count}h", *samples))
    print(f"generated {OUT.name}: {len(SCORE)} counts, {count / RATE:.1f} s, peak {max(map(abs, samples))}/32767")


if __name__ == "__main__":
    main()
