#!/bin/bash

# ==========================================
# CONFIGURATION (Edit these!)
# ==========================================
GOTIFY_TOKEN="AH5NXt3g0lSCyfT"   # <--- Paste your token here
GOTIFY_URL="https://gotify.marlow.quest"
SRC_DIR="$HOME/Videos/Compress"
OUT_DIR="$SRC_DIR/Complete"

# ==========================================
# DEPENDENCY CHECKS
# ==========================================
for cmd in gum HandBrakeCLI curl awk; do
    if ! command -v $cmd &> /dev/null; then
        echo "Error: '$cmd' is not installed."
        exit 1
    fi
done

# Ensure directories exist
mkdir -p "$SRC_DIR"
mkdir -p "$OUT_DIR"

# ==========================================
# GUM UI & SETTINGS
# ==========================================
clear
gum style \
    --border double --border-foreground 240 --foreground 208 \
    --padding "1 6" --margin "1 1" --align center \
    "Video Converter"

# 1. Quality Selection
QUALITY=$(gum input --prompt "Enter Quality Factor (CQ): " --placeholder "35" --width 50)
[ -z "$QUALITY" ] && exit 0
export QUALITY

# 2. Gotify Toggle
if gum confirm "Enable Gotify notification upon completion?" --default=no --affirmative "Yes" --negative "No"; then
    if [ -z "$GOTIFY_TOKEN" ]; then
        gum style --foreground 196 "!! Warning: Gotify enabled but GOTIFY_TOKEN is empty at top of script. Skipping notification."
        GOTIFY_ENABLED=false
    else
        GOTIFY_ENABLED=true
    fi
else
    GOTIFY_ENABLED=false
fi

# ==========================================
# FILE PROCESSING
# ==========================================
shopt -s nocaseglob
shopt -s nullglob
cd "$SRC_DIR" || exit 1
files=( *.mp4 *.mkv *.mov *.avi )

if [ ${#files[@]} -eq 0 ]; then
    gum style --foreground 208 "No video files found in $SRC_DIR."
    exit 0
fi

TOTAL_OLD_BYTES=0
TOTAL_NEW_BYTES=0
FILE_COUNT=0

gum style --foreground 208 --margin "1 0" "Found ${#files[@]} files. Starting queue..."

for f in "${files[@]}"; do
    filename=$(basename -- "$f")
    basename="${filename%.*}"
    export IN_FILE="$f"
    export OUT_FILE="$OUT_DIR/${basename}.mkv"

    # Size calculations
    old_size=$(wc -c < "$f")
    old_mb=$(awk "BEGIN {printf \"%.1f\", $old_size/1048576}")

    # Spinner & Handbrake
    gum spin --spinner minidot --spinner.foreground 208 --title "Encoding: $filename ($old_mb MB)..." -- \
        bash -c 'HandBrakeCLI -i "$IN_FILE" -o "$OUT_FILE" -e svt_av1 --encoder-preset 8 -q "$QUALITY" --vfr -l 1080 -E opus -B 128 > /dev/null 2>&1'
        
    if [ $? -eq 0 ] && [ -f "$OUT_FILE" ]; then
        new_size=$(wc -c < "$OUT_FILE")
        new_mb=$(awk "BEGIN {printf \"%.1f\", $new_size/1048576}")
        saved_mb=$(awk "BEGIN {printf \"%.1f\", $old_mb - $new_mb}")
        
        gum style --foreground 76 "✓ $filename"
        gum style --foreground 245 "  ↳ Size: ${old_mb}MB → ${new_mb}MB (Saved: ${saved_mb}MB)"
        
        TOTAL_OLD_BYTES=$((TOTAL_OLD_BYTES + old_size))
        TOTAL_NEW_BYTES=$((TOTAL_NEW_BYTES + new_size))
        ((FILE_COUNT++))
    else
        gum style --foreground 196 "✗ Failed: $filename" 
    fi
    echo ""
done

# ==========================================
# SUMMARY & NOTIFICATION
# ==========================================
TOTAL_SAVED_MB=$(awk "BEGIN {printf \"%.1f\", ($TOTAL_OLD_BYTES - TOTAL_NEW_BYTES)/1048576}")

gum style \
    --border rounded --border-foreground 208 --foreground 245 \
    --padding "1 2" --margin "1 0" \
    "Batch Complete! Processed: $FILE_COUNT files | Total Saved: $TOTAL_SAVED_MB MB"

if [ "$GOTIFY_ENABLED" = true ] && [ $FILE_COUNT -gt 0 ]; then
    MESSAGE="Finished processing $FILE_COUNT videos. Total space saved: $TOTAL_SAVED_MB MB."
    
    curl -s -S "$GOTIFY_URL/message?token=$GOTIFY_TOKEN" \
        -F "title=✅ Video Encoding Complete" \
        -F "message=$MESSAGE" \
        -F "priority=5" > /dev/null
        
    gum style --foreground 240 "  (Gotify notification sent)"
fi
