#!/usr/bin/env bash
# process_butt_recording.sh
#
# USAGE:
#   ./process_butt_recording.sh <input_recording.mp3|.wav|.ogg|...>
#   All paths must be POSIX-style (in WSL: /mnt/c/... or ~/)
#   Output files are written to the current working directory.
#
# RUNTIME DEPENDENCIES (must be in PATH):
#   ffmpeg      — audio conversion + metadata  (apt install ffmpeg | brew install ffmpeg)
#   metaflac    — FLAC cover art embedding     (apt install flac   | brew install flac)
#
# FILE DEPENDENCIES (relative to this script's location):
#   ./albumart.png  — front cover image (any size; 1:1 recommended)
#
# OUTPUT FORMAT:
#   FLAC: ∆•MIX_100.flac  —  metadata title: ∆•MIX 100
#   MP3:  ∆•MIX_100.mp3   —  320 CBR, ID3v2, same metadata + cover art

set -euo pipefail

# Ensure Unicode patterns work consistently across macOS/Linux/WSL
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ALBUMART="$SCRIPT_DIR/albumart.png"

# --- Input validation ---
if [ $# -lt 1 ]; then
    echo "Usage: $0 <input_file>"
    exit 1
fi
input="$1"
if [ ! -f "$input" ]; then
    echo "ERROR: input file not found: $input"
    exit 1
fi

# --- Date extraction ---
# Expects YYYYMMDD somewhere in the filename (BUTT default: stream_YYYYMMDD_HHMMSS.ext)
# Takes the first 8-digit sequence found; prompts for manual entry if not found.
raw_date=$(basename "$input" | grep -oE '[0-9]{8}' | head -1)
if [ -z "$raw_date" ]; then
    echo "WARNING: could not find YYYYMMDD date in filename."
    read -rp "Enter date manually (YYYY-MM-DD): " date_string
    # Validate basic format
    if ! echo "$date_string" | grep -qE '^[0-9]{4}-[0-9]{2}-[0-9]{2}$'; then
        echo "ERROR: invalid date format '$date_string' — expected YYYY-MM-DD"
        exit 1
    fi
else
    date_string="${raw_date:0:4}-${raw_date:4:2}-${raw_date:6:2}"
fi

# --- Mix number extraction ---
# Matches ∆•MIXnn or ∆•MIXnnn (2-3 digits). Prompts if not found.
# Uses POSIX character classes + explicit chars to stay portable across grep variants.
mixnumber_string=$(basename "$input" | grep -oP '[\x{2206}\x{0394}]\x{2022}MIX\d{2,3}' 2>/dev/null \
    || basename "$input" | grep -oE '[∆Δ]•MIX[0-9]{2,3}' || true)
mixnumber_raw="${mixnumber_string##*MIX}"

echo "Detected mix: '${mixnumber_string:-<none>}'  →  number: '${mixnumber_raw:-<none>}'"

if [ -z "$mixnumber_raw" ]; then
    read -rp "Could not detect mix number. Enter it manually: " mixnumber_raw
fi

# Strip any leading zeros before re-padding (avoids octal issues with printf)
mixnumber_raw=$((10#${mixnumber_raw}))
mixnumber=$(printf '%03d' "$mixnumber_raw")

# Output filenames and metadata
title="∆•MIX $mixnumber"
flac_out="∆•MIX_${mixnumber}.flac"
mp3_out="∆•MIX_${mixnumber}.mp3"

echo "Date:        $date_string"
echo "Title:       $title"
echo "FLAC output: $flac_out"
echo "MP3 output:  $mp3_out"
echo ""

# --- Step 1: Convert + trim silence → FLAC ---
echo "=== Converting to FLAC ==="
ffmpeg -y -i "$input" \
    -af "silenceremove=start_periods=1:start_threshold=-50dB:start_duration=3:start_silence=4:detection=rms,silenceremove=stop_periods=1:stop_threshold=-60dB:stop_duration=7:stop_silence=0.5:detection=rms" \
    -c:a flac \
    -metadata artist="∆•RYZ" \
    -metadata album="∆•MIX" \
    -metadata album_artist="∆•RYZ" \
    -metadata date="$date_string" \
    -metadata title="$title" \
    -metadata comment="deltaryz.com" \
    -metadata track="$mixnumber_raw" \
    "$flac_out"

# --- Step 2: Embed cover art in FLAC ---
if [ -f "$ALBUMART" ]; then
    echo "=== Embedding cover art in FLAC ==="
    metaflac --import-picture-from="$ALBUMART" "$flac_out"
else
    echo "WARNING: $ALBUMART not found — FLAC has no cover art"
fi

# --- Step 3: FLAC → MP3 320 CBR with cover art ---
echo "=== Converting to MP3 ==="
if [ -f "$ALBUMART" ]; then
    ffmpeg -y -i "$flac_out" -i "$ALBUMART" \
        -map 0:a -map 1:v \
        -c:a libmp3lame -b:a 320k -q:a 0 \
        -c:v copy \
        -id3v2_version 3 \
        -metadata:s:v title="Album cover" \
        -metadata:s:v comment="Cover (front)" \
        "$mp3_out"
else
    ffmpeg -y -i "$flac_out" \
        -c:a libmp3lame -b:a 320k -q:a 0 \
        "$mp3_out"
    echo "WARNING: $ALBUMART not found — MP3 has no cover art"
fi

echo ""
echo "=== Done ==="
echo "  $flac_out"
echo "  $mp3_out"
