#!/bin/bash
# DSS Setup Script
# Automated installation and configuration for Design System Server

set -e  # Exit on error

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

# Functions
print_header() {
    echo -e "${BLUE}============================================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}============================================================${NC}"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

# Check prerequisites
check_prerequisites() {
    print_header "Checking Prerequisites"

    # Check Python version
    if ! command -v python3 &> /dev/null; then
        print_error "Python 3 is not installed"
        exit 1
    fi

    PYTHON_VERSION=$(python3 --version | cut -d' ' -f2)
    print_success "Python $PYTHON_VERSION found"

    # Check Python version >= 3.10
    if ! python3 -c "import sys; exit(0 if sys.version_info >= (3, 10) else 1)"; then
        print_error "Python 3.10+ is required (found $PYTHON_VERSION)"
        exit 1
    fi

    # Check pip
    if ! command -v pip3 &> /dev/null; then
        print_error "pip3 is not installed"
        exit 1
    fi
    print_success "pip3 found"

    # Check git (optional but recommended)
    if command -v git &> /dev/null; then
        print_success "git found"
    else
        print_warning "git not found (optional)"
    fi
}

# Create virtual environment
setup_venv() {
    print_header "Setting Up Virtual Environment"

    if [ -d ".venv" ]; then
        print_warning "Virtual environment already exists"
        read -p "Recreate it? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            rm -rf .venv
            print_info "Removed existing virtual environment"
        else
            print_info "Using existing virtual environment"
            return
        fi
    fi

    python3 -m venv .venv
    print_success "Virtual environment created"
}

# Activate virtual environment
activate_venv() {
    print_info "Activating virtual environment..."
    source .venv/bin/activate
    print_success "Virtual environment activated"
}

# Install dependencies
install_dependencies() {
    print_header "Installing Dependencies"

    # Upgrade pip
    print_info "Upgrading pip..."
    pip install --upgrade pip > /dev/null 2>&1
    print_success "pip upgraded"

    # Install requirements
    if [ -f "requirements.txt" ]; then
        print_info "Installing packages from requirements.txt..."
        pip install -r requirements.txt
        print_success "Dependencies installed"
    else
        print_error "requirements.txt not found"
        exit 1
    fi

    # Install Playwright browsers for Chrome DevTools
    print_info "Installing Playwright browsers (for Chrome DevTools MCP)..."
    if python3 -c "import playwright" 2>/dev/null; then
        playwright install chromium > /dev/null 2>&1
        print_success "Playwright Chromium browser installed"
    else
        print_warning "Playwright not available, skipping browser install"
    fi
}

# Create directories
create_directories() {
    print_header "Creating Project Directories"

    mkdir -p .dss/cache
    mkdir -p .dss/logs
    print_success "Directories created"
}

# Setup environment file
setup_env() {
    print_header "Setting Up Environment Variables"

    if [ -f ".env" ]; then
        print_warning ".env file already exists"
        return
    fi

    if [ -f ".env.example" ]; then
        cp .env.example .env
        print_success ".env file created from .env.example"
        print_warning "Please edit .env and add your FIGMA_TOKEN"
    else
        print_error ".env.example not found"
    fi
}

# Run tests
run_tests() {
    print_header "Running Tests"

    print_info "Running test suite..."
    if python3 test_quick.py; then
        print_success "All tests passed!"
    else
        print_warning "Some tests failed (this is OK for first setup)"
    fi
}

# Print next steps
print_next_steps() {
    print_header "Setup Complete!"

    echo ""
    echo -e "${GREEN}✓ DSS is ready to use!${NC}"
    echo ""
    echo "Next steps:"
    echo ""
    echo "1. Activate the virtual environment:"
    echo -e "   ${BLUE}source .venv/bin/activate${NC}"
    echo ""
    echo "2. Add your Figma token to .env:"
    echo -e "   ${BLUE}FIGMA_TOKEN=figd_...${NC}"
    echo ""
    echo "3. Start the REST API server:"
    echo -e "   ${BLUE}python -m tools.api.server${NC}"
    echo ""
    echo "4. Start the MCP server (in another terminal):"
    echo -e "   ${BLUE}python -m tools.api.mcp_server${NC}"
    echo ""
    echo "5. Read the quickstart guide:"
    echo -e "   ${BLUE}cat docs/QUICKSTART.md${NC}"
    echo ""
    echo -e "${YELLOW}Documentation:${NC}"
    echo "  - Quickstart: docs/QUICKSTART.md"
    echo "  - Architecture: docs/ARCHITECTURE.md"
    echo "  - API Reference: README.md"
    echo "  - Examples: examples/"
    echo ""
}

# Main installation flow
main() {
    echo ""
    print_header "DSS (Design System Server) Setup"
    echo ""

    check_prerequisites
    setup_venv
    activate_venv
    install_dependencies
    create_directories
    setup_env
    run_tests
    print_next_steps
}

# Run main function
main
