#!/bin/bash
version="beta-1.0.1"
self="$(basename "$0")"

# Default verbose flag
VERBOSE=""

# Parse arguments for --version and --verbose
while [[ "$1" != "" ]]; do
    case "$1" in
        --version)
            echo "$self version $version"
            exit 0
            ;;
        --verbose)
            VERBOSE="--verbose"
            shift
            ;;
        -e)
            shift
            code="$1"
            [[ -z "$code" ]] && { echo "❌ No code provided after -e"; exit 1; }

            tmpfile=$(mktemp "/tmp/code.XXXXXX")
            tmpfile="$tmpfile.💩"
            printf "%s\n" "$code" > "$tmpfile"

            # Compile & run directly with verbose if needed
            "$dir/☠️" "$tmpfile" $VERBOSE || exit 1
            rm -f "$tmpfile"
            exit 0
            ;;
        *)
            break
            ;;
    esac
done

file="$1"
shift || true
dir="$(dirname "$0")"
name="${file%.*}"
ext="${file##*.}"

SOURCE_EXTS=("💩" "poop" "poo" "shit" "caca" "crap" "dung" "feces" "turd" "doo-doo" "💩💩" "💩💩💩" "💩💩💩💩" "dump" "dumpy")
COMPILED_EXTS=("☠️" "skull" "dead" "rekt" "die" "rip")  

find_file_with_extensions() {
    local base="$1"
    shift
    local extensions=("$@")
    for ext in "${extensions[@]}"; do
        if [[ -f "$base.$ext" ]]; then
            echo "$base.$ext"
            return 0
        fi
    done
    return 1
}

# Normalize filename and pass verbose along
if [[ " ${SOURCE_EXTS[*]} " == *" $ext "* ]]; then
    [[ ! -f "$file" ]] && file=$(find_file_with_extensions "$name" "${SOURCE_EXTS[@]}")
    [[ -z "$file" ]] && { echo "❌ Source file not found"; exit 1; }
    "$dir/☠️" "$file" $VERBOSE || exit 1
    compiled=$(find_file_with_extensions "$name" "${COMPILED_EXTS[@]}")
    [[ -z "$compiled" ]] && { echo "❌ Compiled file not found"; exit 1; }
    "$dir/💩.raku" "$compiled" $VERBOSE

elif [[ " ${COMPILED_EXTS[*]} " == *" $ext "* ]]; then
    [[ ! -f "$file" ]] && file=$(find_file_with_extensions "$name" "${COMPILED_EXTS[@]}")
    [[ -z "$file" ]] && { echo "❌ Compiled file not found"; exit 1; }
    raku "$dir/💩.raku" "$file" $VERBOSE

else
    echo "❌ Unsupported file type: $file"
    exit 1
fi
