#!/bin/bash
# scripts/setup.sh — First-time setup for AI Proxy
set -e

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

echo -e "${GREEN}=== AI Proxy Setup ===${NC}"
echo ""

# 1. Check Python
if ! command -v python3 &>/dev/null; then
    echo -e "${RED}Python 3.11+ required. Install it first.${NC}"
    exit 1
fi

PY_VERSION=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
echo -e "Python: ${GREEN}${PY_VERSION}${NC}"

# 2. Create venv
if [ ! -d ".venv" ]; then
    echo "Creating virtual environment..."
    python3 -m venv .venv
fi
source .venv/bin/activate

# 3. Install
echo "Installing proxym..."
pip install -e ".[test,dev]" -q

# 4. Create .env from template
if [ ! -f ".env" ]; then
    cp .env.example .env
    echo -e "${YELLOW}Created .env from template — edit it with your API keys${NC}"
else
    echo ".env already exists"
fi

# 5. Check Docker/Podman
if command -v docker &>/dev/null; then
    echo -e "Container runtime: ${GREEN}Docker$(docker --version | grep -oP '\d+\.\d+\.\d+')${NC}"
elif command -v podman &>/dev/null; then
    echo -e "Container runtime: ${GREEN}Podman $(podman --version | grep -oP '\d+\.\d+\.\d+')${NC}"
else
    echo -e "${YELLOW}No container runtime found. Install Docker or Podman for Redis/Ollama.${NC}"
fi

# 6. Start Redis
echo ""
echo "Starting Redis..."
if command -v docker &>/dev/null; then
    docker run -d --name proxym-redis -p 6379:6379 redis/redis-stack:latest 2>/dev/null || \
        echo "Redis already running or port in use"
elif command -v podman &>/dev/null; then
    podman run -d --name proxym-redis -p 6379:6379 docker.io/redis/redis-stack:latest 2>/dev/null || \
        echo "Redis already running or port in use"
else
    echo -e "${YELLOW}Skipping Redis (no container runtime). Install redis-server natively or use Docker.${NC}"
fi

# 7. Check Ollama
echo ""
if command -v ollama &>/dev/null; then
    echo -e "Ollama: ${GREEN}installed${NC}"
    echo "Pulling recommended models..."
    ollama pull qwen2.5-coder:1.5b 2>/dev/null &
    echo "  (pulling qwen2.5-coder:1.5b in background)"
elif curl -sf http://localhost:11434/api/version >/dev/null 2>&1; then
    echo -e "Ollama: ${GREEN}running (remote/docker)${NC}"
else
    echo -e "${YELLOW}Ollama not found. Install from https://ollama.com or use Docker.${NC}"
fi

# 8. Run tests
echo ""
echo "Running unit tests..."
python -m pytest tests/ -x -q --ignore=tests/test_e2e.py 2>/dev/null || \
    echo -e "${YELLOW}Some tests failed (expected if Redis/Ollama not ready)${NC}"

echo ""
echo -e "${GREEN}=== Setup Complete ===${NC}"
echo ""
echo "Next steps:"
echo "  1. Edit .env with your API keys (at minimum ANTHROPIC_API_KEY)"
echo "  2. Start the proxy:  proxym"
echo "  3. Test it:          curl http://localhost:4000/health"
echo "  4. Use from IDE:     Set API Base = http://localhost:4000"
echo ""
echo "Or use Docker Compose:"
echo "  docker compose up -d"
echo ""
