#!/bin/bash

# --- Configuration & Theme ---
ORANGE="#FF8700"
GREY="#808080"

# Styling functions
title_style() { gum style --foreground "$ORANGE" --bold --border double --border-foreground "$GREY" --padding "0 2" --margin "1" "$1"; }
info_style() { gum style --foreground "$GREY" "$1"; }
error_style() { gum style --foreground "#FF0000" --bold "Error: $1"; }

# --- Initialization ---
clear
title_style "NDS ROM PATCHER"

# 1. Select the Folder
info_style "Navigate to the folder containing your ROM and Patch:"
TARGET_DIR=$(gum file --directory --cursor.foreground "$ORANGE")

# Exit if no directory selected
[[ -z "$TARGET_DIR" ]] && exit 1

cd "$TARGET_DIR" || exit 1

# 2. Identify Files
# Find .nds files
NDS_FILES=$(ls *.nds 2>/dev/null)
if [[ -z "$NDS_FILES" ]]; then
    error_style "No .nds files found in $TARGET_DIR"
    exit 1
fi

# Find .xdelta files
PATCH_FILES=$(ls *.xdelta 2>/dev/null)
if [[ -z "$PATCH_FILES" ]]; then
    error_style "No .xdelta files found in $TARGET_DIR"
    exit 1
fi

# 3. User Selection (if multiple files exist)
ROM=$(echo "$NDS_FILES" | gum choose --header "Select the NDS ROM" --cursor.foreground "$ORANGE" --header.foreground "$GREY")
PATCH=$(echo "$PATCH_FILES" | gum choose --header "Select the xdelta patch" --cursor.foreground "$ORANGE" --header.foreground "$GREY")

# 4. Prepare Output Name
# Strips extension and adds -patch.nds
FILENAME=$(basename "$ROM" .nds)
OUTPUT="${FILENAME}-patch.nds"

# 5. Execute Patching
echo ""
gum spin --spinner dot --title "Applying patch to $ROM..." --title.foreground "$ORANGE" -- \
    xdelta3 -d -s "$ROM" "$PATCH" "$OUTPUT"

# 6. Result Check
if [ $? -eq 0 ]; then
    gum style --foreground "$ORANGE" --border rounded --border-foreground "$GREY" --padding "1 2" \
        "SUCCESS!" "File created: $OUTPUT"
else
    error_style "Patching failed. Ensure your ROM is a clean dump."
fi
