#!/usr/bin/env bash
# Setup script for electron-angle-patcher development environment
# Supports uv (fast) or falls back to venv (standard)

set -euo pipefail

# 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

# Functions
info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

header() {
    echo -e "${CYAN}$1${NC}"
}

check_python() {
    header "=== Checking Python version ==="
    if ! command -v python3 &> /dev/null; then
        error "python3 not found. Please install Python 3.10 or higher."
        exit 1
    fi

    PYTHON_VERSION=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
    PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d. -f1)
    PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d. -f2)

    if [ "$PYTHON_MAJOR" -lt 3 ] || ([ "$PYTHON_MAJOR" -eq 3 ] && [ "$PYTHON_MINOR" -lt 10 ]); then
        error "Python 3.10 or higher is required (found $PYTHON_VERSION)"
        exit 1
    fi

    info "Python $PYTHON_VERSION found ✓"
}

check_uv() {
    header "=== Checking for uv ==="
    if command -v uv &> /dev/null; then
        UV_VERSION=$(uv --version 2>/dev/null || echo "unknown")
        info "uv $UV_VERSION found ✓"
        return 0
    else
        warn "uv not found (optional, but recommended)"
        return 1
    fi
}

install_uv() {
    header "=== Installing uv ==="
    info "Installing uv (fast Python package manager)..."
    curl -LsSf https://astral.sh/uv/install.sh | sh

    # Add uv to PATH for this session
    export PATH="$HOME/.local/bin:$PATH"

    if command -v uv &> /dev/null; then
        info "uv installed successfully ✓"
        return 0
    else
        warn "uv installation completed, but not found in PATH"
        warn "You may need to restart your shell or run: export PATH=\"\$HOME/.local/bin:\$PATH\""
        return 1
    fi
}

setup_environment() {
    header "=== Setting up environment ==="

    if command -v uv &> /dev/null; then
        info "Using uv (fast mode)..."
        if [ -d ".venv" ]; then
            warn ".venv already exists, skipping creation"
        else
            uv venv
            info "Virtual environment created with uv ✓"
        fi

        info "Installing dependencies with uv..."
        uv pip install -e ".[dev]"
        info "Dependencies installed ✓"
    else
        info "Using venv (standard mode)..."
        if [ -d ".venv" ]; then
            warn ".venv already exists, skipping creation"
        else
            python3 -m venv .venv
            info "Virtual environment created ✓"
        fi

        info "Installing dependencies..."
        .venv/bin/pip install --upgrade pip setuptools wheel
        .venv/bin/pip install -e ".[dev]"
        info "Dependencies installed ✓"
    fi
}

run_tests() {
    header "=== Running tests ==="

    if command -v uv &> /dev/null; then
        info "Running tests with uv..."
        uv run pytest tests/ -v
    else
        info "Running tests..."
        .venv/bin/python -m pytest tests/ -v
    fi

    info "Tests completed ✓"
}

print_summary() {
    header "=== Setup Complete! ==="
    echo ""
    info "Your development environment is ready."
    echo ""
    echo -e "${CYAN}Quick Start:${NC}"
    echo "  Activate environment:  source .venv/bin/activate"
    echo "  Run patcher:           make run"
    echo "  List apps only:        make run-list"
    echo "  Run tests:             make test"
    echo "  Format code:           make fmt"
    echo "  Check code:            make check"
    echo ""
    echo -e "${CYAN}Or use uv directly (if installed):${NC}"
    echo "  Run patcher:           uv run python -m electron_angle_patcher.cli"
    echo "  Run tests:             uv run pytest"
    echo ""
    echo -e "${CYAN}Use 'make help' to see all available commands${NC}"
    echo ""
}

main() {
    header "╔════════════════════════════════════════════════════════════╗"
    header "║  Electron Angle Patcher - Development Environment Setup  ║"
    header "╚════════════════════════════════════════════════════════════╝"
    echo ""

    check_python
    echo ""

    # Check if uv is installed
    USE_VENV=false
    if check_uv; then
        USE_UV=true
    else
        USE_UV=false
        echo ""
    fi

    # Ask if user wants to install uv
    if [ "$USE_UV" = false ]; then
        echo ""
        read -p "Would you like to install uv for faster setup? (y/N) " -n 1 -r
        echo ""
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            if install_uv; then
                USE_UV=true
            fi
        fi
    fi

    echo ""
    setup_environment
    echo ""

    # Ask if user wants to run tests
    read -p "Run tests now? (y/N) " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo ""
        run_tests
        echo ""
    fi

    print_summary
}

main