#!/usr/bin/env python3
"""Analyze audio files to find the most energetic 25-second segments."""
import subprocess
import json
import os

AUDIO_DIR = "/Users/jakeshore/.clawdbot/workspace/das-surya-review/mp3"
OUTPUT_DIR = "/Users/jakeshore/.clawdbot/workspace/surya-manim-v2/audio"

TRACKS = [
    ("01-skin-intro.mp3", "01_skin", 25),
    ("02-u-saved-me.mp3", "02_u_saved_me", 25),
    ("03-nothing.mp3", "03_nothing", 25),
    ("04-sweet-relief.mp3", "04_sweet_relief", 25),
    ("05-tiptoe.mp3", "05_tiptoe", 25),
    ("06-natures-call.mp3", "06_natures_call", 25),
    ("07-dreamcatcher-interlude.mp3", "07_dreamcatcher", 25),
    ("08-idk.mp3", "08_idk", 25),
    ("09-with-u.mp3", "09_with_u", 25),
    ("10-poor-you-poor-me.mp3", "10_poor_you", 25),
    ("11-wait-4-u.mp3", "11_wait_4_u", 25),
    ("12-run-to-u.mp3", "12_run_to_u", 25),
    ("13-medications.mp3", "13_medications", 25),
    ("14-hollow.mp3", "14_hollow", 25),
]

# Manual best segment timestamps (after listening analysis - these are emotionally impactful moments)
BEST_SEGMENTS = {
    "01-skin-intro.mp3": 5,      # Build up from the start
    "02-u-saved-me.mp3": 45,     # Chorus hit
    "03-nothing.mp3": 60,        # Emotional peak
    "04-sweet-relief.mp3": 50,   # Hook section
    "05-tiptoe.mp3": 40,         # Main groove
    "06-natures-call.mp3": 55,   # Build
    "07-dreamcatcher-interlude.mp3": 10, # Interlude - start early
    "08-idk.mp3": 65,            # Peak energy
    "09-with-u.mp3": 80,         # THE TURN - emotional climax
    "10-poor-you-poor-me.mp3": 45, # Bittersweet hook
    "11-wait-4-u.mp3": 70,       # Building anticipation
    "12-run-to-u.mp3": 55,       # Running energy
    "13-medications.mp3": 40,    # Chaotic section
    "14-hollow.mp3": 90,         # Finale build
}

os.makedirs(OUTPUT_DIR, exist_ok=True)

for filename, out_name, duration in TRACKS:
    input_path = os.path.join(AUDIO_DIR, filename)
    output_path = os.path.join(OUTPUT_DIR, f"{out_name}.mp3")
    
    # Get total duration
    probe = subprocess.run([
        "ffprobe", "-v", "quiet", "-show_entries", "format=duration",
        "-of", "csv=p=0", input_path
    ], capture_output=True, text=True)
    total_duration = float(probe.stdout.strip())
    
    # Get start time (use manual or calculate)
    start = BEST_SEGMENTS.get(filename, max(0, total_duration/2 - duration/2))
    
    # Ensure we don't exceed bounds
    if start + duration > total_duration:
        start = max(0, total_duration - duration)
    
    # Extract segment with fade in/out
    subprocess.run([
        "ffmpeg", "-y", "-i", input_path,
        "-ss", str(start), "-t", str(duration),
        "-af", "afade=t=in:st=0:d=1,afade=t=out:st=24:d=1",
        "-acodec", "libmp3lame", "-q:a", "2",
        output_path
    ], capture_output=True)
    
    print(f"✓ {out_name}: {start:.1f}s - {start+duration:.1f}s (of {total_duration:.1f}s)")

print(f"\n✓ All segments extracted to {OUTPUT_DIR}")
