#!/bin/bash
# Environment validation for Trax project

set -e

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

echo -e "${BLUE}🔍 Trax Environment Check${NC}"
echo "================================"

ISSUES=0

# Check Python version
echo -e "\n${YELLOW}Python:${NC}"
if command -v python3.11 &> /dev/null; then
    PYTHON_CMD="python3.11"
    version=$($PYTHON_CMD --version | cut -d' ' -f2)
    echo -e "  ${GREEN}✅ Python $version${NC}"
elif command -v python3 &> /dev/null; then
    PYTHON_CMD="python3"
    version=$($PYTHON_CMD --version | cut -d' ' -f2)
    major=$(echo $version | cut -d'.' -f1)
    minor=$(echo $version | cut -d'.' -f2)
    if [ "$major" -eq 3 ] && [ "$minor" -ge 11 ]; then
        echo -e "  ${GREEN}✅ Python $version${NC}"
    else
        echo -e "  ${RED}❌ Python 3.11+ required (found $version)${NC}"
        ((ISSUES++))
    fi
else
    echo -e "  ${RED}❌ Python not found${NC}"
    ((ISSUES++))
fi

# Check uv
echo -e "\n${YELLOW}Package Manager:${NC}"
if command -v uv &> /dev/null; then
    version=$(uv --version | cut -d' ' -f2)
    echo -e "  ${GREEN}✅ uv $version${NC}"
else
    echo -e "  ${RED}❌ uv not installed${NC}"
    echo -e "  ${YELLOW}💡 Install with: curl -LsSf https://astral.sh/uv/install.sh | sh${NC}"
    ((ISSUES++))
fi

# Check virtual environment
echo -e "\n${YELLOW}Virtual Environment:${NC}"
if [ -d ".venv" ]; then
    echo -e "  ${GREEN}✅ .venv exists${NC}"
    if [ -f ".venv/bin/activate" ]; then
        echo -e "  ${GREEN}✅ Activation script found${NC}"
    else
        echo -e "  ${RED}❌ Activation script missing${NC}"
        ((ISSUES++))
    fi
else
    echo -e "  ${YELLOW}⚠️  Virtual environment not created${NC}"
    echo -e "  ${YELLOW}💡 Run: uv venv${NC}"
fi

# Check API keys
echo -e "\n${YELLOW}API Keys:${NC}"
cd "$(dirname "$0")/.."
source .venv/bin/activate 2>/dev/null || true

python3 << 'EOF'
import sys
sys.path.insert(0, 'src')
try:
    from config import config
    
    # Essential keys
    essential = {
        'DEEPSEEK_API_KEY': config.DEEPSEEK_API_KEY,
        'ANTHROPIC_API_KEY': config.ANTHROPIC_API_KEY,
    }
    
    # Optional keys
    optional = {
        'OPENAI_API_KEY': config.OPENAI_API_KEY,
        'PERPLEXITY_API_KEY': config.PERPLEXITY_API_KEY,
        'DIRECTUS_TOKEN': config.DIRECTUS_TOKEN,
    }
    
    print("  Essential:")
    for key, value in essential.items():
        if value:
            print(f"    ✅ {key}: {'*' * 10}")
        else:
            print(f"    ❌ {key}: Not set")
    
    print("  Optional:")
    for key, value in optional.items():
        if value:
            print(f"    ✅ {key}: {'*' * 10}")
        else:
            print(f"    ⚠️  {key}: Not set")
    
    # Show available services
    services = config.get_available_ai_services()
    if services:
        print(f"\n  Available AI Services: {', '.join(services)}")
    
except Exception as e:
    print(f"  ❌ Error checking API keys: {e}")
    sys.exit(1)
EOF

# Check PostgreSQL
echo -e "\n${YELLOW}PostgreSQL:${NC}"
if command -v psql &> /dev/null; then
    version=$(psql --version | head -1)
    echo -e "  ${GREEN}✅ $version${NC}"
    
    # Try to connect to default database
    if psql -U postgres -d postgres -c "SELECT 1;" &> /dev/null; then
        echo -e "  ${GREEN}✅ Can connect to PostgreSQL${NC}"
    else
        echo -e "  ${YELLOW}⚠️  Cannot connect to PostgreSQL${NC}"
        echo -e "  ${YELLOW}💡 Check your PostgreSQL service is running${NC}"
    fi
else
    echo -e "  ${RED}❌ PostgreSQL not installed${NC}"
    echo -e "  ${YELLOW}💡 Install with: brew install postgresql@15${NC}"
    ((ISSUES++))
fi

# Check FFmpeg
echo -e "\n${YELLOW}FFmpeg:${NC}"
if command -v ffmpeg &> /dev/null; then
    version=$(ffmpeg -version | head -1)
    echo -e "  ${GREEN}✅ $version${NC}"
else
    echo -e "  ${RED}❌ FFmpeg not installed${NC}"
    echo -e "  ${YELLOW}💡 Install with: brew install ffmpeg${NC}"
    ((ISSUES++))
fi

# Check Task Master
echo -e "\n${YELLOW}Task Master:${NC}"
if [ -d ".taskmaster" ]; then
    echo -e "  ${GREEN}✅ .taskmaster directory exists${NC}"
    if [ -f ".taskmaster/tasks/tasks.json" ]; then
        task_count=$(python3 -c "import json; print(len(json.load(open('.taskmaster/tasks/tasks.json'))['tasks']))" 2>/dev/null || echo "0")
        echo -e "  ${GREEN}✅ tasks.json found ($task_count tasks)${NC}"
    else
        echo -e "  ${YELLOW}⚠️  tasks.json not found${NC}"
    fi
else
    echo -e "  ${YELLOW}⚠️  Task Master not initialized${NC}"
    echo -e "  ${YELLOW}💡 Run: task-master init${NC}"
fi

# Check project structure
echo -e "\n${YELLOW}Project Structure:${NC}"
required_dirs=("src" "tests" "docs" "scripts" "data")
for dir in "${required_dirs[@]}"; do
    if [ -d "$dir" ]; then
        echo -e "  ${GREEN}✅ $dir/${NC}"
    else
        echo -e "  ${YELLOW}⚠️  $dir/ missing${NC}"
    fi
done

# Summary
echo -e "\n${BLUE}Summary:${NC}"
echo "================================"
if [ $ISSUES -eq 0 ]; then
    echo -e "${GREEN}✅ Environment is ready!${NC}"
else
    echo -e "${RED}❌ Found $ISSUES critical issues${NC}"
    echo -e "${YELLOW}Run setup_dev.sh to fix most issues${NC}"
fi