#!/bin/bash

# Universal Nushell Script Runner
# Auto-detects nushell, checks version consistency, and runs nu scripts

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Get script directory and repository root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"

# Function to show usage
show_usage() {
    echo -e "${BLUE}Universal Nushell Script Runner${NC}"
    echo ""
    echo "Usage: $0 [OPTIONS] SCRIPT [SCRIPT_ARGS...]"
    echo ""
    echo "Options:"
    echo -e "  ${GREEN}--check-only${NC}        Only check version, don't run script"
    echo -e "  ${GREEN}--fix${NC}               Auto-fix version mismatches"
    echo -e "  ${GREEN}--no-version-check${NC}  Skip version checking (not recommended)"
    echo -e "  ${GREEN}--help, -h${NC}          Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 plugin_status.nu            # Run plugin status with version check"
    echo "  $0 --fix build_all.nu          # Fix version issues then build"
    echo "  $0 --check-only                # Only check version consistency"
    echo ""
}

# Function to check if nushell is installed
check_nushell_installed() {
    if ! command -v nu &> /dev/null; then
        echo -e "${RED}❌ Nushell (nu) is not installed or not in PATH${NC}"
        echo -e "${YELLOW}🔧 Installing nushell from submodule...${NC}"

        if [[ -f "scripts/sh/update_nushell.sh" ]]; then
            if bash scripts/sh/update_nushell.sh update; then
                echo -e "${GREEN}✅ Nushell installed successfully${NC}"
                return 0
            else
                echo -e "${RED}❌ Failed to install nushell${NC}"
                echo "Please install manually: https://www.nushell.sh/book/installation.html"
                return 1
            fi
        else
            echo -e "${RED}❌ update_nushell.sh not found${NC}"
            echo "Please install nushell manually: https://www.nushell.sh/book/installation.html"
            return 1
        fi
    fi
    return 0
}

# Function to check version consistency
check_version_consistency() {
    local fix_flag="$1"

    echo -e "${CYAN}🔍 Checking nushell version consistency...${NC}"

    if [[ -f "scripts/check_version.nu" ]]; then
        local check_args=""
        if [[ "$fix_flag" == "true" ]]; then
            check_args="--fix"
        fi

        # Try project binary first (more reliable), fall back to system nu
        local nu_bin="nu"
        if [[ -f "nushell/target/release/nu" ]]; then
            nu_bin="nushell/target/release/nu"
        fi

        if $nu_bin scripts/check_version.nu $check_args >/dev/null 2>&1; then
            echo -e "${GREEN}✅ Version check passed${NC}"
            return 0
        else
            echo -e "${RED}❌ Version check failed${NC}"
            if [[ "$fix_flag" != "true" ]]; then
                echo -e "${YELLOW}💡 Run with --fix to automatically resolve version issues${NC}"
            fi
            return 1
        fi
    else
        echo -e "${YELLOW}⚠️  Version checker not found, skipping version check${NC}"
        return 0
    fi
}

# Function to run nushell script
run_script() {
    local script_name="$1"
    shift
    local script_args="$@"

    # Try different possible paths for the script
    local script_paths=(
        "scripts/$script_name"
        "scripts/nu/$script_name"
        "$script_name"
    )

    local script_path=""
    for path in "${script_paths[@]}"; do
        if [[ -f "$path" ]]; then
            script_path="$path"
            break
        fi
    done

    if [[ -z "$script_path" ]]; then
        echo -e "${RED}❌ Script not found: $script_name${NC}"
        echo "Searched in:"
        for path in "${script_paths[@]}"; do
            echo "  - $path"
        done
        return 1
    fi

    # Determine which nu binary to use (project first, then system)
    local nu_bin="nu"
    if [[ -f "nushell/target/release/nu" ]]; then
        nu_bin="nushell/target/release/nu"
    fi

    echo -e "${BLUE}🚀 Running: $nu_bin $script_path $script_args${NC}"
    echo ""

    # Execute the nushell script
    if $nu_bin "$script_path" $script_args; then
        echo ""
        echo -e "${GREEN}✅ Script completed successfully${NC}"
        return 0
    else
        echo ""
        echo -e "${RED}❌ Script failed${NC}"
        return 1
    fi
}

# Parse command line arguments
FIX_VERSION=false
SKIP_VERSION_CHECK=false
CHECK_ONLY=false
SCRIPT_NAME=""
SCRIPT_ARGS=()

while [[ $# -gt 0 ]]; do
    case $1 in
        --check-only)
            CHECK_ONLY=true
            shift
            ;;
        --fix)
            FIX_VERSION=true
            shift
            ;;
        --no-version-check)
            SKIP_VERSION_CHECK=true
            shift
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        -*)
            echo -e "${RED}❌ Unknown option: $1${NC}"
            echo ""
            show_usage
            exit 1
            ;;
        *)
            SCRIPT_NAME="$1"
            shift
            SCRIPT_ARGS=("$@")
            break
            ;;
    esac
done

# Main execution flow

# 1. Check if nushell is installed
if ! check_nushell_installed; then
    exit 1
fi

# 2. Check version consistency (unless explicitly skipped)
if [[ "$SKIP_VERSION_CHECK" != "true" ]]; then
    if ! check_version_consistency "$FIX_VERSION"; then
        echo ""
        echo -e "${RED}❌ Version check failed. Please fix version issues before continuing.${NC}"
        echo -e "${YELLOW}💡 Use --fix flag to automatically resolve version issues${NC}"
        echo -e "${YELLOW}💡 Or use --no-version-check to skip (not recommended)${NC}"
        exit 1
    fi
fi

# 3. If check-only mode, exit after version check
if [[ "$CHECK_ONLY" == "true" ]]; then
    echo -e "${GREEN}✅ Version check completed${NC}"
    exit 0
fi

# 4. Ensure script name is provided
if [[ -z "$SCRIPT_NAME" ]]; then
    echo -e "${RED}❌ No script specified${NC}"
    echo ""
    show_usage
    exit 1
fi

# 5. Run the requested script
if run_script "$SCRIPT_NAME" "${SCRIPT_ARGS[@]}"; then
    exit 0
else
    exit 1
fi