#!/bin/bash

# Define Colors
ORANGE="#FFA500"
GREY="#808080"

# 1. Check for required tools
for cmd in gum wit dolphin-tool; do
    if ! command -v $cmd &> /dev/null; then
        gum style --foreground 196 "Error: '$cmd' is not installed."
        [ "$cmd" == "dolphin-tool" ] && echo "Hint: Install it via your package manager (usually part of dolphin-emu)."
        exit 1
    fi
done

# 2. Aesthetic Header
clear
gum style \
	--border double \
	--border-foreground "$ORANGE" \
	--foreground "$ORANGE" \
	--margin "1 2" \
	--padding "1 4" \
	--align center \
	--width 50 \
	"NINTENDO USB LOADER"

# 3. Mode Selection
gum style --foreground "$GREY" " > Select the console format:"
MODE=$(gum choose --cursor.foreground "$ORANGE" "Wii (WBFS)" "GameCube (ISO)")
[ -z "$MODE" ] && exit 1

# 4. Source Directory & File Selection
gum style --foreground "$GREY" " > Step 1: Select the FOLDER containing your games"
ISO_DIR=$(gum file --directory)
[ -z "$ISO_DIR" ] && exit 1

# Move into the folder to get clean filenames
pushd "$ISO_DIR" > /dev/null
shopt -s nullglob
available_files=(*.iso *.rvz)

if [ ${#available_files[@]} -eq 0 ]; then
    gum style --foreground 196 " No .iso or .rvz files found in $ISO_DIR"
    popd > /dev/null
    exit 1
fi

gum style --foreground "$GREY" " > Step 2: Select the GAMES to transfer"
gum style --foreground "$GREY" "   (Use SPACE to select multiple, ENTER to confirm)"
SELECTED_FILES=$(gum choose --no-limit --cursor.foreground "$ORANGE" --selected.foreground "$ORANGE" "${available_files[@]}")
popd > /dev/null

[ -z "$SELECTED_FILES" ] && exit 1

# Read the multiline selection from Gum into a safe Bash array
mapfile -t selected_array <<< "$SELECTED_FILES"

# 5. USB Selection
USER_MEDIA="/run/media/$USER"
if [ ! -d "$USER_MEDIA" ] || [ -z "$(ls -A "$USER_MEDIA" 2>/dev/null)" ]; then
    gum style --foreground 196 " No USB drives detected in $USER_MEDIA"
    exit 1
fi

gum style --foreground "$GREY" " > Select your destination USB drive"
pushd "$USER_MEDIA" > /dev/null
SELECTED_DRIVE=$(gum choose --cursor.foreground "$ORANGE" *)
popd > /dev/null
[ -z "$SELECTED_DRIVE" ] && exit 1

USB_DIR="$USER_MEDIA/$SELECTED_DRIVE"

# 6. Final Summary and Confirmation
clear
gum style --foreground "$ORANGE" "Ready to Process ${#selected_array[@]} $MODE title(s)"
echo -e "  \033[90mTarget: \033[0m $USB_DIR"
echo ""

gum confirm --selected.background "$ORANGE" "Begin transfer?" || exit 0

# 7. Processing Loop
clear
gum style --foreground "$ORANGE" "Processing titles..."
echo ""

for filename in "${selected_array[@]}"; do
    full_path="$ISO_DIR/$filename"
    ext="${filename##*.}"
    base_name="${filename%.*}"
    
    # Defaults
    needs_cleanup=false
    working_iso="$full_path"

    # --- RVZ UNPACKING LOGIC ---
    if [ "${ext,,}" == "rvz" ]; then
        working_iso="$ISO_DIR/${base_name}_temp.iso"
        
        gum spin --spinner dot --title.foreground "$GREY" --title "Unpacking RVZ: $filename..." -- \
        dolphin-tool convert -i "$full_path" -o "$working_iso" -f iso
        
        if [ $? -ne 0 ]; then
            gum style --foreground 196 "  ✘ Failed to unpack: $filename"
            continue
        fi
        # Flag the temporary ISO for deletion once we are done with it
        needs_cleanup=true
    fi

    # --- TRANSFER LOGIC ---
    if [ "$MODE" == "Wii (WBFS)" ]; then
        # WII LOGIC
        gum spin --spinner dot --title.foreground "$GREY" --title "Converting to WBFS: $base_name..." -- \
        wit copy "$working_iso" --wbfs --split --dest "$USB_DIR/wbfs/%T [%I]/%I.wbfs"
        
        if [ $? -eq 0 ]; then
            gum style --foreground "$ORANGE" "  ✔ $base_name"
        else
            gum style --foreground 196 "  ✘ Failed transfer: $base_name"
        fi

    else
        # GAMECUBE LOGIC
        game_id=$(wit id "$working_iso" 2>/dev/null | tail -n 1 | awk '{print $1}')
        clean_title=$(echo "$base_name" | tr -d ':/\\*?<>|')
        DEST_FOLDER="$USB_DIR/games/$clean_title [$game_id]"

        if [[ ! "$game_id" =~ ^[A-Z0-9]{6}$ ]]; then
            gum style --foreground 196 "  ✘ Failed: $base_name (Invalid Game ID)"
        else
            gum spin --spinner dot --title.foreground "$GREY" --title "Moving: $clean_title..." -- \
            bash -c 'mkdir -p "$1" && cp "$2" "$1/game.iso"' _ "$DEST_FOLDER" "$working_iso"

            if [ $? -eq 0 ]; then
                gum style --foreground "$ORANGE" "  ✔ $clean_title"
            else
                gum style --foreground 196 "  ✘ Failed: $clean_title"
            fi
        fi
    fi

    # --- CLEANUP LOGIC ---
    if [ "$needs_cleanup" = true ]; then
        rm -f "$working_iso"
    fi
done

# 8. Finished
echo ""
gum style \
	--border rounded \
	--border-foreground "$GREY" \
	--foreground "$ORANGE" \
	--padding "1 2" \
	"COMPLETE: Games synced to $SELECTED_DRIVE"