"""Split a long voice track into ~N-second chunks, cutting only in pauses.

Usage: python split_on_pauses.py long.wav 30
Writes chunk_000.wav, chunk_001.wav, ... next to the input (16 kHz mono WAV).
Needs ffmpeg on PATH.
"""
import re, subprocess, sys
from pathlib import Path

src = Path(sys.argv[1])
target = float(sys.argv[2]) if len(sys.argv) > 2 else 30.0

dur = float(subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
                            '-of', 'csv=p=0', str(src)], capture_output=True, text=True).stdout)
log = subprocess.run(['ffmpeg', '-hide_banner', '-i', str(src), '-af', 'silencedetect=noise=-30dB:d=0.3',
                      '-f', 'null', '-'], capture_output=True, text=True).stderr
starts = [float(x) for x in re.findall(r'silence_start: ([\d.]+)', log)]
ends = [float(x) for x in re.findall(r'silence_end: ([\d.]+)', log)]
pauses = [(s + e) / 2 for s, e in zip(starts, ends)]  # middle of each pause

cuts, last = [], 0.0
while dur - last > target * 1.5:
    want = last + target
    ok = [p for p in pauses if last + target * 0.5 < p < last + target * 1.5]
    cut = min(ok, key=lambda p: abs(p - want)) if ok else want  # no pause found: hard cut
    cuts.append(round(cut, 3)); last = cut

points = [0.0] + cuts + [dur]
for i, (a, b) in enumerate(zip(points, points[1:])):
    out = src.with_name(f'chunk_{i:03d}.wav')
    subprocess.run(['ffmpeg', '-v', 'error', '-y', '-i', str(src), '-ss', str(a), '-to', str(b),
                    '-ar', '16000', '-ac', '1', str(out)], check=True)
    print(f'{out.name}  {a:7.2f}s -> {b:7.2f}s  ({b - a:5.2f}s)')
