#!/usr/bin/env bash
set -euo pipefail

# Cinematic C2 — Full Stack Proof of Concept
#
# Usage:
#   ./demo.sh              Full auto (generate, embed, launch 2 peers, inject)
#   ./demo.sh generate     Generate video + embed C2 tracks only
#   ./demo.sh peer1        Launch first peer
#   ./demo.sh peer2        Launch second peer
#   ./demo.sh inject       Inject a live pause command
#   ./demo.sh info         Show embedded block schedule

ROOT="$(cd "$(dirname "$0")" && pwd)"
DEMO_DIR="$ROOT/demo_output"
SOURCE_VIDEO="$DEMO_DIR/source.mkv"
EMBEDDED_MKV="$DEMO_DIR/demo.mkv"
SCHEDULE="$ROOT/tests/fixtures/demo_schedule.json"
SHIM="$ROOT/target/debug/cc2-shim"
SOCK1="/tmp/cc2-peer1.sock"
SOCK2="/tmp/cc2-peer2.sock"

check_prereqs() {
    local need_mpv="${1:-false}"
    local missing=()
    command -v ffmpeg >/dev/null || missing+=(ffmpeg)
    command -v mkvmerge >/dev/null || missing+=(mkvmerge)
    command -v mkvpropedit >/dev/null || missing+=(mkvpropedit)
    command -v python3 >/dev/null || missing+=(python3)
    command -v cargo >/dev/null || missing+=(cargo)
    if [ "$need_mpv" = "true" ]; then
        command -v mpv >/dev/null || missing+=(mpv)
    fi

    if [ ${#missing[@]} -gt 0 ]; then
        echo "ERROR: Missing prerequisites: ${missing[*]}"
        echo "Install with: sudo apt install ffmpeg mkvtoolnix mpv python3"
        exit 1
    fi
    echo "[OK] All prerequisites found"
}

generate_video() {
    mkdir -p "$DEMO_DIR"

    if [ -f "$SOURCE_VIDEO" ]; then
        echo "[SKIP] Source video already exists: $SOURCE_VIDEO"
    else
        echo "[GEN] Creating 50s test video with timecode overlay..."
        ffmpeg -y -f lavfi \
            -i "testsrc2=duration=50:size=1280x720:rate=30" \
            -f lavfi -i "sine=frequency=440:duration=50" \
            -vf "drawtext=text='%{pts\:hms}':fontsize=72:fontcolor=white:x=(w-tw)/2:y=h-th-40:box=1:boxcolor=black@0.5:boxborderw=10" \
            -c:v libx264 -preset ultrafast -pix_fmt yuv420p \
            -c:a aac -shortest \
            "$SOURCE_VIDEO" 2>/dev/null
        echo "[OK] Source video: $SOURCE_VIDEO"
    fi
}

embed_tracks() {
    if [ -f "$EMBEDDED_MKV" ]; then
        echo "[SKIP] Embedded MKV already exists: $EMBEDDED_MKV"
        return
    fi

    echo "[EMBED] Embedding C2 tracks..."
    python3 "$ROOT/tools/mkvembed.py" \
        --input "$SOURCE_VIDEO" \
        --schedule "$SCHEDULE" \
        --output "$EMBEDDED_MKV"
    echo "[OK] Embedded MKV: $EMBEDDED_MKV"
}

build_shim() {
    echo "[BUILD] Building cc2-shim..."
    cargo build -p cc2-shim 2>&1 | tail -5
    echo "[OK] Built: $SHIM"
}

show_info() {
    echo "[INFO] Block schedule:"
    "$SHIM" info --file "$EMBEDDED_MKV"
}

launch_peer() {
    local peer_num="$1"
    local sock="/tmp/cc2-peer${peer_num}.sock"
    local peer_arg="${2:-}"

    echo "[PLAY] Launching peer $peer_num (socket: $sock)..."
    if [ -n "$peer_arg" ]; then
        RUST_LOG=info "$SHIM" play \
            --file "$EMBEDDED_MKV" \
            --video "$SOURCE_VIDEO" \
            --ipc-socket "$sock" \
            --launch-mpv \
            --peer "$peer_arg"
    else
        RUST_LOG=info "$SHIM" play \
            --file "$EMBEDDED_MKV" \
            --video "$SOURCE_VIDEO" \
            --ipc-socket "$sock" \
            --launch-mpv
    fi
}

inject_cmd() {
    local peer_id="${1:?Usage: inject <peer_endpoint_id> [action] [message]}"
    local action="${2:-appevent}"
    local message="${3:-Hello Mucho}"

    echo "[INJECT] Injecting $action to peer $peer_id..."
    RUST_LOG=info "$SHIM" inject \
        --file "$EMBEDDED_MKV" \
        --action "$action" \
        --message "$message" \
        --pts-anchor 0 \
        --peer "$peer_id"
    echo "[OK] Live command broadcast"
}

cleanup() {
    echo ""
    echo "[CLEANUP] Stopping background processes..."
    jobs -p 2>/dev/null | xargs -r kill 2>/dev/null || true
    rm -f "$SOCK1" "$SOCK2"
    echo "[OK] Done"
}

case "${1:-auto}" in
    generate)
        check_prereqs false
        generate_video
        embed_tracks
        build_shim
        show_info
        ;;
    peer1)
        launch_peer 1 "${2:-}"
        ;;
    peer2)
        launch_peer 2 "${2:-}"
        ;;
    inject)
        inject_cmd "${2:-}" "${3:-appevent}" "${4:-Hello Mucho}"
        ;;
    info)
        build_shim
        show_info
        ;;
    auto)
        echo "=== Cross-machine demo ==="
        echo ""
        echo "On machine A (first peer):"
        echo "  ./demo.sh generate"
        echo "  ./demo.sh peer1"
        echo "  # Note the endpoint_id from the log output"
        echo ""
        echo "On machine B (copy demo.mkv + source.mkv, then):"
        echo "  ./demo.sh peer2 <endpoint_id_from_A>"
        echo ""
        echo "To inject a message:"
        echo "  ./demo.sh inject <endpoint_id> appevent 'Hello Mucho'"
        echo ""
        echo "For local single-machine test:"
        check_prereqs true
        generate_video
        embed_tracks
        build_shim
        echo ""
        show_info
        echo ""
        echo "=== Launching Peer 1 ==="
        echo "=== Watch for 'endpoint_id' in the log below ==="
        launch_peer 1
        ;;
    *)
        echo "Usage: $0 [generate|peer1|peer2|inject|info|auto]"
        echo ""
        echo "  generate             Generate video + embed C2 tracks"
        echo "  peer1 [endpoint_id]  Launch first peer (prints its endpoint ID)"
        echo "  peer2 <endpoint_id>  Launch second peer (connects to first)"
        echo "  inject <endpoint_id> [action] [message]"
        echo "                       Inject a live command (default: appevent 'Hello Mucho')"
        echo "  info                 Show embedded block schedule"
        echo "  auto                 Show cross-machine instructions + launch peer1"
        exit 1
        ;;
esac
