#!/bin/bash

# Fixed script to convert ProRes 4444 alpha to HEVC alpha
# Usage: ./test_prores_to_hevc.sh input.mov

if [ $# -eq 0 ]; then
    echo "Usage: $0 input_prores4444.mov"
    echo "Example: ./test_prores_to_hevc.sh animation.mov"
    exit 1
fi

prores_file="$1"

# Check if input file exists
if [ ! -f "$prores_file" ]; then
    echo "Error: File '$prores_file' not found."
    exit 1
fi

# Generate output filename
base_name=$(basename "$prores_file" .mov)
hevc_output="${base_name}_hevc.mov"

echo "=== Testing ProRes 4444 to HEVC Alpha Conversion ==="
echo "Input ProRes:  $prores_file"
echo "Output HEVC:   $hevc_output"
echo ""

# Check input file properties
echo "=== Input File Analysis ==="
echo "ProRes file properties:"
ffprobe -v quiet -select_streams v:0 -show_entries stream=codec_name,pix_fmt,width,height,bit_rate -of csv=p=0 "$prores_file"
echo ""

# Check if input has alpha channel (HEVC embeds alpha natively)
has_alpha=$(ffprobe -v quiet -select_streams v:0 -show_entries stream=pix_fmt -of csv=p=0 "$prores_file" | grep -E "(yuva|rgba|argb|bgra|abgr)")
if [ -z "$has_alpha" ]; then
    echo "Note: Input shows standard pixel format (HEVC will embed alpha natively if present)"
fi

# Show input file size
input_size=$(stat -f%z "$prores_file" 2>/dev/null || stat -c%s "$prores_file" 2>/dev/null)
echo "Input file size: $(awk "BEGIN {printf \"%.1f\", $input_size/1024/1024}")MB"
echo ""

# Test if VideoToolbox supports HEVC on this system
echo "=== Testing VideoToolbox HEVC Support ==="
vt_test=$(ffmpeg -f lavfi -i "color=red:size=100x100:duration=1" -c:v hevc_videotoolbox -f null - 2>&1)
if echo "$vt_test" | grep -q "not supported\|failed\|error"; then
    echo "VideoToolbox doesn't support HEVC on this system, falling back to software encoder"
    use_software=true
else
    echo "VideoToolbox HEVC support detected"
    use_software=false
fi
echo ""

# Convert ProRes 4444 to HEVC Alpha with improved settings
echo "=== Converting ProRes 4444 to HEVC Alpha ==="

if [ "$use_software" = true ]; then
    # Software encoder fallback matching Apple's settings
    echo "Using software HEVC encoder (libx265)..."
    cmd="ffmpeg -y -i \"$prores_file\" -map 0:a -map 0:v -c:a aac -b:a 129k -c:v libx265 -b:v 4885k -preset medium -colorspace bt709 -color_primaries bt709 -color_trc bt709 -movflags +faststart \"$hevc_output\""
    echo "Command: $cmd"
    echo ""

    ffmpeg -y -i "$prores_file" \
        -map 0:a -map 0:v \
        -c:a aac -b:a 129k \
        -c:v libx265 \
        -b:v 4885k \
        -preset medium \
        -colorspace bt709 \
        -color_primaries bt709 \
        -color_trc bt709 \
        -movflags +faststart \
        "$hevc_output"
else
    # VideoToolbox matching Apple's exact Encode Media output
    echo "Using VideoToolbox HEVC encoder (matching Apple's exact Encode Media)..."
    cmd="ffmpeg -y -i \"$prores_file\" -map 0:a -map 0:v -c:a aac -b:a 129k -c:v hevc_videotoolbox -b:v 4885k -colorspace bt709 -color_primaries bt709 -color_trc bt709 -vtag hvc1 -movflags +faststart \"$hevc_output\""
    echo "Command: $cmd"
    echo ""

    ffmpeg -y -i "$prores_file" \
        -c:v hevc_videotoolbox \
        -pix_fmt bgra \
        -alpha_quality 1 \
        -tag:v hvc1 \
        "$hevc_output"
fi

if [ $? -eq 0 ] && [ -f "$hevc_output" ]; then
    echo ""
    echo "✓ SUCCESS: HEVC conversion complete!"
    ls -lh "$hevc_output"

    # Verify the output file isn't corrupted
    echo ""
    echo "=== Verifying Output File Integrity ==="
    verify_result=$(ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_frames -of csv=p=0 "$hevc_output" 2>&1)
    if echo "$verify_result" | grep -q "error\|corrupt\|invalid"; then
        echo "✗ WARNING: Output file may be corrupted"
        echo "Verification result: $verify_result"
    else
        echo "✓ Output file integrity verified"
        echo "Frame count: $verify_result"
    fi

    # Show file size comparison
    output_size=$(stat -f%z "$hevc_output" 2>/dev/null || stat -c%s "$hevc_output" 2>/dev/null)
    if [ ! -z "$input_size" ] && [ ! -z "$output_size" ]; then
        ratio=$(awk "BEGIN {printf \"%.1f\", $output_size/$input_size}")
        compression=$(awk "BEGIN {printf \"%.1f\", $input_size/$output_size}")
        echo ""
        echo "=== File Size Comparison ==="
        echo "ProRes 4444: $(awk "BEGIN {printf \"%.1f\", $input_size/1024/1024}")MB"
        echo "HEVC Alpha:  $(awk "BEGIN {printf \"%.1f\", $output_size/1024/1024}")MB"
        echo "Size ratio:  ${ratio}x (${compression}x compression)"
    fi

    echo ""
    echo "=== Output File Analysis ==="
    echo "HEVC file properties:"
    ffprobe -v quiet -select_streams v:0 -show_entries stream=codec_name,pix_fmt,width,height,bit_rate -of csv=p=0 "$hevc_output"

    # HEVC embeds alpha natively - visual verification required
    echo "✓ HEVC file created (alpha embedded natively - verify visually)"

    echo ""
    echo "✓ TEST COMPLETE: $hevc_output created successfully!"
    echo "✓ Open the file in Safari or QuickTime to verify alpha transparency works!"

else
    echo ""
    echo "✗ FAILED: HEVC conversion failed"

    # Try alternative approach if VideoToolbox failed
    if [ "$use_software" = false ]; then
        echo ""
        echo "Trying software encoder as fallback..."

        ffmpeg -y -i "$prores_file" \
            -map 0:a -map 0:v \
            -c:a aac -b:a 129k \
            -c:v libx265 \
            -b:v 4885k \
            -preset medium \
            -colorspace bt709 \
            -color_primaries bt709 \
            -color_trc bt709 \
            -movflags +faststart \
            "${base_name}_hevc_sw.mov"

        if [ $? -eq 0 ]; then
            echo "✓ SUCCESS with software encoder: ${base_name}_hevc_sw.mov"
        else
            echo "✗ Both hardware and software encoders failed"
            exit 1
        fi
    else
        exit 1
    fi
fi
