#!/bin/bash
# Pololu DSL Runner - Universal Bash Entry Point
# Auto-detects Python environment and runs DSL scripts

set -e

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

# Find project root
find_project_root() {
    local dir="$PWD"
    while [[ "$dir" != "/" ]]; do
        if [[ -f "$dir/pololu/__init__.py" ]] || [[ -d "$dir/.venv" ]] || [[ -d "$dir/venv" ]]; then
            echo "$dir"
            return 0
        fi
        if [[ -d "$dir/.git" ]]; then
            echo "$dir"
            return 0
        fi
        dir="$(dirname "$dir")"
    done
    return 1
}

# Find Python interpreter
find_python() {
    local project_root="$1"

    # 1. Check if already in virtual environment
    if [[ -n "$VIRTUAL_ENV" ]]; then
        if command -v python3 &> /dev/null; then
            echo "python3"
            return 0
        fi
    fi

    # 2. Look for venv in project root
    for venv_name in .venv venv env .env; do
        local venv_path="$project_root/$venv_name"
        if [[ -f "$venv_path/bin/python3" ]]; then
            echo "$venv_path/bin/python3"
            return 0
        fi
        if [[ -f "$venv_path/bin/python" ]]; then
            echo "$venv_path/bin/python"
            return 0
        fi
    done

    # 3. Check for system python3 with ticlib
    if command -v python3 &> /dev/null; then
        if python3 -c "import ticlib" 2>/dev/null; then
            echo "python3"
            return 0
        fi
    fi

    return 1
}

# Auto-setup virtual environment
auto_setup_venv() {
    local project_root="$1"

    echo -e "${YELLOW}⚠️  Python environment with ticlib not found${NC}"
    echo ""

    # Check if we should create venv
    if [[ ! -d "$project_root/.venv" ]] && [[ ! -d "$project_root/venv" ]]; then
        echo "Creating virtual environment..."
        if command -v python3 &> /dev/null; then
            python3 -m venv "$project_root/.venv"
            echo -e "${GREEN}✅ Virtual environment created${NC}"
        else
            echo -e "${RED}❌ Python3 not found${NC}"
            return 1
        fi
    fi

    # Find the venv
    local venv_path=""
    for venv_name in .venv venv; do
        if [[ -d "$project_root/$venv_name" ]]; then
            venv_path="$project_root/$venv_name"
            break
        fi
    done

    if [[ -z "$venv_path" ]]; then
        echo -e "${RED}❌ Could not find virtual environment${NC}"
        return 1
    fi

    # Check if ticlib is installed
    local python_bin="$venv_path/bin/python3"
    if [[ ! -f "$python_bin" ]]; then
        python_bin="$venv_path/bin/python"
    fi

    if ! "$python_bin" -c "import ticlib" 2>/dev/null; then
        echo "Installing ticlib..."
        "$python_bin" -m pip install ticlib
        echo -e "${GREEN}✅ ticlib installed${NC}"
    fi

    # Add pololu package to path if needed
    if ! "$python_bin" -c "import pololu" 2>/dev/null; then
        echo "Adding pololu package to Python path..."
        # Create .pth file
        echo "$project_root" > "$venv_path/lib/python*/site-packages/pololu.pth" 2>/dev/null || \
        echo "$project_root" > "$($python_bin -c 'import site; print(site.getsitepackages()[0])')/pololu.pth" 2>/dev/null || \
        export PYTHONPATH="$project_root:$PYTHONPATH"
    fi

    echo ""
    echo -e "${GREEN}✅ Environment ready${NC}"
    echo ""

    return 0
}

# Main function
main() {
    # Show help if no arguments
    if [[ $# -eq 0 ]]; then
        echo "Pololu DSL Runner"
        echo ""
        echo "Usage: pololu-dsl <script.dsl> [options]"
        echo ""
        echo "Options:"
        echo "  -n, --dry-run       Parse only, do not execute"
        echo "  -d, --diagnostic    Run full diagnostic before execution"
        echo "  --no-auto-fix       Disable automatic environment setup"
        echo "  -h, --help          Show this help"
        echo ""
        echo "Examples:"
        echo "  pololu-dsl examples/dsl/basic_test.dsl"
        echo "  pololu-dsl my_script.dsl --diagnostic"
        echo "  pololu-dsl script.dsl --dry-run"
        exit 0
    fi

    # Parse arguments
    local script=""
    local dsl_args=()

    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                main
                exit 0
                ;;
            -n|--dry-run)
                dsl_args+=("--dry-run")
                shift
                ;;
            -d|--diagnostic)
                dsl_args+=("--diagnostic")
                shift
                ;;
            --no-auto-fix)
                dsl_args+=("--no-auto-fix")
                shift
                ;;
            -*)
                echo "Unknown option: $1"
                exit 1
                ;;
            *)
                if [[ -z "$script" ]]; then
                    script="$1"
                fi
                shift
                ;;
        esac
    done

    if [[ -z "$script" ]]; then
        echo -e "${RED}❌ Error: No script file specified${NC}"
        exit 1
    fi

    if [[ ! -f "$script" ]]; then
        echo -e "${RED}❌ Error: Script not found: $script${NC}"
        exit 1
    fi

    # Find project root
    local project_root
    project_root=$(find_project_root) || {
        echo -e "${RED}❌ Error: Could not find project root${NC}"
        exit 1
    }

    echo "Project root: $project_root"

    # Find Python
    local python_bin
    python_bin=$(find_python "$project_root") || {
        # Try auto-setup
        if [[ " ${dsl_args[*]} " != *" --no-auto-fix "* ]]; then
            auto_setup_venv "$project_root" || exit 1
            # Try again
            python_bin=$(find_python "$project_root") || {
                echo -e "${RED}❌ Error: Could not configure Python environment${NC}"
                exit 1
            }
        else
            echo -e "${RED}❌ Error: Python environment with ticlib not found${NC}"
            echo "Run: source .venv/bin/activate"
            exit 1
        fi
    }

    echo "Python: $python_bin"
    echo ""

    # Export PYTHONPATH to ensure pololu package is available
    export PYTHONPATH="$project_root:$PYTHONPATH"

    # Run DSL runner
    exec "$python_bin" -m pololu.dsl_runner "$script" "${dsl_args[@]}"
}

main "$@"
