"""Generate reproducible, non-musical test signals; no downloaded music."""
import array
import hashlib
import json
import math
from pathlib import Path
import subprocess
import sys
import wave

ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / 'artifacts/runtime/content-trust/audio'
OUT.mkdir(parents=True, exist_ok=True)
SPECS = [
    (12, 44100, 1, 'wav'), (24, 48000, 2, 'wav'),
    (36, 44100, 2, 'wav'), (48, 32000, 1, 'wav'),
    (60, 48000, 2, 'wav'), (75, 44100, 1, 'm4a'),
    (90, 48000, 2, 'm4a'), (105, 44100, 2, 'm4a'),
    (120, 44100, 1, 'mp3'), (150, 48000, 2, 'mp3'),
]
records = []
for index, (duration, rate, channels, ext) in enumerate(SPECS, 1):
    name = f'signal-{index:02d}'
    pcm = array.array('h')
    frequency = 170 + index * 37
    for frame in range(duration * rate):
        second = frame / rate
        envelope = min(1, second / .05, (duration - second) / .05)
        pulse = .65 + .35 * math.sin(2 * math.pi * .5 * second)
        for channel in range(channels):
            value = .2 * envelope * pulse * (math.sin(2 * math.pi * (frequency + channel * 13) * second) + .2 * math.sin(2 * math.pi * frequency * 2 * second))
            pcm.append(round(max(-1, min(1, value)) * 32767))
    if sys.byteorder != 'little':
        pcm.byteswap()
    wav = OUT / (name + '.wav')
    with wave.open(str(wav), 'wb') as stream:
        stream.setnchannels(channels)
        stream.setsampwidth(2)
        stream.setframerate(rate)
        stream.writeframes(pcm.tobytes())
    output = OUT / (name + '.' + ext)
    if ext != 'wav':
        codec = ['-c:a', 'aac', '-b:a', '128k'] if ext == 'm4a' else ['-c:a', 'libmp3lame', '-b:a', '160k']
        subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', '-i', str(wav), *codec, str(output)], check=True)
    probe = json.loads(subprocess.check_output(['ffprobe', '-v', 'error', '-show_format', '-show_streams', '-of', 'json', str(output)]))
    audio = next(s for s in probe['streams'] if s['codec_type'] == 'audio')
    records.append({'id': f'00000000-0000-4000-8000-{index:012d}', 'name': name, 'title': f'Generated test signal {index:02d}', 'file': output.name, 'duration': duration, 'sourceDuration': float(probe['format']['duration']), 'sampleRate': rate, 'channels': channels, 'sourceCodec': audio['codec_name'], 'sourceBitRate': int(audio.get('bit_rate', 0)), 'sourceBytes': output.stat().st_size, 'sourceSha256': hashlib.sha256(output.read_bytes()).hexdigest(), 'frequency': frequency})
metadata = {'kind': 'self-generated deterministic test signals, not Suno songs', 'generator': 'scripts/generate-audio-fixtures.py', 'ffmpeg': subprocess.check_output(['ffmpeg', '-version']).decode().splitlines()[0], 'samples': records}
(OUT / 'fixtures.json').write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
print(json.dumps({'samples': len(records), 'sourceBytes': sum(row['sourceBytes'] for row in records), 'output': str(OUT)}))
