#!/bin/bash
# Reel Villarroel v2: rotación correcta + tip Roger + música ambiente
# Rotación: SIN transpose, SIN noautorotate → ffmpeg auto-rota portrait correctamente
set -e
RAW="/root/instagram-insights/reels/villarroel/raw"
TMP="/root/instagram-insights/reels/villarroel/tmp2"
VOICE="/tmp/villarroel.mp3"
BGMUS="/tmp/bgmusic.mp3"
OUT="/root/instagram-insights/reels/villarroel/villarroel_v2.mp4"

mkdir -p "$TMP"
VF="scale=1080:1920,setsar=1,fps=30"

echo "=== Paso 1: Segmentos ==="
# Seg1: 0-4s  — Roger hablando (tip)
echo "[1/7] IMG_2322 tip Roger ss=18..."
ffmpeg -y -ss 18 -t 4 -i "$RAW/IMG_2322 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg1.mp4" 2>/dev/null && echo "  OK"

# Seg2: 4-6s  — Aerial calle desde ático (hook)
echo "[2/7] IMG_2320 aerial ss=0.5..."
ffmpeg -y -ss 0.5 -t 2 -i "$RAW/IMG_2320 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg2.mp4" 2>/dev/null && echo "  OK"

# Seg3: 6-9s  — Fachada Eixample (contexto)
echo "[3/7] IMG_2327 Eixample..."
ffmpeg -y -ss 0 -t 3 -i "$RAW/IMG_2327 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg3.mp4" 2>/dev/null && echo "  OK"

# Seg4: 9-14s — Corredero + vertical instalado
echo "[4/7] IMG_2358 producto ss=2..."
ffmpeg -y -ss 2 -t 5 -i "$RAW/IMG_2358 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg4.mp4" 2>/dev/null && echo "  OK"

# Seg5: 14-18s — Macro tejido microperforado
echo "[5/7] IMG_2343 tejido..."
ffmpeg -y -ss 0 -t 4 -i "$RAW/IMG_2343 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg5.mp4" 2>/dev/null && echo "  OK"

# Seg6: 18-21s — Vista desde dentro (privacidad)
echo "[6/7] IMG_2364 interior..."
ffmpeg -y -ss 0 -t 3 -i "$RAW/IMG_2364 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg6.mp4" 2>/dev/null && echo "  OK"

# Seg7: 21-22.4s — Ático con mobiliario (cierre)
echo "[7/7] IMG_2373 cierre..."
ffmpeg -y -ss 0 -t 1.4 -i "$RAW/IMG_2373 2.MOV" -vf "$VF" \
  -c:v libx264 -preset fast -crf 20 -an "$TMP/seg7.mp4" 2>/dev/null && echo "  OK"

echo ""
echo "=== Paso 2: Concat + Audio (voz Roger + ambiente) ==="
cat > "$TMP/concat.txt" << EOF
file 'seg1.mp4'
file 'seg2.mp4'
file 'seg3.mp4'
file 'seg4.mp4'
file 'seg5.mp4'
file 'seg6.mp4'
file 'seg7.mp4'
EOF

ffmpeg -y \
  -f concat -safe 0 -i "$TMP/concat.txt" \
  -i "$VOICE" \
  -i "$BGMUS" \
  -filter_complex \
    "[1:a]volume=1.0[vox];[2:a]volume=0.18,atrim=end=22.5[bg];[vox][bg]amix=inputs=2:duration=first[aout]" \
  -map "0:v" -map "[aout]" \
  -c:v copy \
  -c:a aac -b:a 192k \
  -shortest \
  "$OUT" 2>/dev/null

echo ""
echo "=== Resultado ==="
ls -lh "$OUT"
ffprobe -v quiet -show_entries stream=width,height,codec_name -show_entries format=duration \
  -of default=noprint_wrappers=1 "$OUT" 2>/dev/null | grep -v "^N/A"
rm -rf "$TMP"
echo "✔ Listo"
