#!/bin/bash
################################################################################
# Setup script for PyCharter development environment
#
# Creates venv, installs dev dependencies, optional API deps, Jupyter kernel,
# and pre-commit hooks. Run from repo root or any directory:
#   ./setup.sh
#   /path/to/pycharter/setup.sh
################################################################################

set -euo pipefail

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

info() { echo -e "${BLUE}ℹ${NC} $1"; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warning() { echo -e "${YELLOW}⚠${NC} $1"; }
error() { echo -e "${RED}✗${NC} $1" >&2; }

################################################################################
# Script directory and repo root
################################################################################
SCRIPT_DIR=$(cd -- "$(dirname "${BASH_SOURCE[0]:-.}")" &>/dev/null && pwd)
cd "$SCRIPT_DIR" || exit 1

# Check if Python 3 is available
if ! command -v python3 &> /dev/null; then
    error "Python 3 is not installed. Please install Python 3.10 or higher."
    exit 1
fi

# Check Python version (requires 3.10+)
PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $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 version: $PYTHON_VERSION"
echo ""

# Create virtual environment (or recreate if broken, e.g. missing venv/bin/activate)
if [ ! -d "venv" ] || [ ! -f "venv/bin/activate" ]; then
    if [ -d "venv" ]; then
        info "Removing broken or incomplete virtual environment..."
        rm -rf venv
    fi
    info "Creating virtual environment..."
    python3 -m venv venv
    success "Virtual environment created"
else
    success "Virtual environment already exists"
fi

# Activate virtual environment
info "Activating virtual environment..."
source venv/bin/activate

# Upgrade pip, setuptools, wheel
info "Upgrading pip, setuptools, and wheel..."
pip install --upgrade pip setuptools wheel --quiet

# Install package in development mode
info "Installing PyCharter in development mode..."
if pip install -e ".[dev]" --quiet; then
    success "PyCharter installed with dev dependencies"
else
    error "Failed to install PyCharter. Check the error messages above."
    exit 1
fi

# Install API dependencies if requested or if API exists (src layout)
if [ -d "src/pycharter/api" ]; then
    info "Installing API dependencies (required for API server)..."
    if pip install -e ".[api]" --quiet; then
        success "API dependencies installed"
    else
        warning "Failed to install API dependencies. API server may not work."
    fi
fi

# Pre-commit hooks (same as statfyi-scraper-api: run on commit so CI stays green)
if command -v pre-commit &> /dev/null; then
    info "Installing pre-commit hooks..."
    pre-commit install
    success "Pre-commit hooks installed."
else
    warning "pre-commit not found. Install with: pip install pre-commit && pre-commit install"
fi

# Create Jupyter kernel for this environment
# Note: Jupyter Lab and ipykernel are already installed via dev dependencies
KERNEL_NAME="pycharter-dev"
KERNEL_DISPLAY_NAME="Python (pycharter-dev)"

info "Setting up Jupyter kernel..."
# Remove existing kernel if it exists (ignore errors)
jupyter kernelspec remove "$KERNEL_NAME" --quiet 2>/dev/null || true

# Create new kernel
if python -m ipykernel install --user --name="$KERNEL_NAME" --display-name="$KERNEL_DISPLAY_NAME" 2>/dev/null; then
    success "Jupyter kernel '$KERNEL_DISPLAY_NAME' created"
else
    warning "Failed to create Jupyter kernel. You can create it manually later."
fi

echo ""
success "Setup complete!"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📋 Quick Start"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "To activate the environment:"
echo "  source venv/bin/activate"
echo ""
echo "To start development servers:"
echo "  pycharter api    # Start API server (http://localhost:8000)"
echo "  pycharter ui dev # Start UI dev server (http://localhost:3000)"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📓 Jupyter Lab"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "To start Jupyter Lab:"
echo "  1. Activate the environment: source venv/bin/activate"
echo "  2. Start Jupyter Lab: jupyter lab"
echo "  3. Select kernel: '$KERNEL_DISPLAY_NAME'"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🧪 Testing"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Run tests:"
echo "  pytest"
echo ""
echo "Run tests with coverage:"
echo "  pytest --cov=pycharter"
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "💡 Development Tips"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "• Package is installed in editable mode (-e), so code changes are"
echo "  reflected immediately (restart kernel/server to see changes)"
echo ""
echo "• To verify the kernel is using the right environment, run in a notebook:"
echo "  import sys; print(sys.executable)"
echo ""
echo "• To list all available kernels:"
echo "  jupyter kernelspec list"
echo ""
