#!/bin/bash
version="test"

# Detect which command was actually run (works through symlinks)
self="$(basename "$0")"

# Handle version flag for any alias
if [[ "$1" == "--version" ]]; then
    echo "$self version $version"
    exit 0
fi

# Handle -e flag for inline code
if [[ "$1" == "-e" ]]; then
    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
    ☠️ "$tmpfile" || exit 1
    rm -f "$tmpfile"
    exit 0
fi


file="$1"
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");  

# Function to find real file based on base name + extension list
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
if [[ " ${SOURCE_EXTS[*]} " == *" $ext "* ]]; then
    # If file exists, use it
    if [[ ! -f "$file" ]]; then
        file=$(find_file_with_extensions "$name" "${SOURCE_EXTS[@]}")
        [[ -z "$file" ]] && { echo "❌ Source file not found"; exit 1; }
    fi
    "$dir/☠️" "$file" || exit 1
    compiled=$(find_file_with_extensions "$name" "${COMPILED_EXTS[@]}")
    [[ -z "$compiled" ]] && { echo "❌ Compiled file not found"; exit 1; }
    "$dir/💩.raku" "$compiled"

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

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