#!/bin/bash

# Test script for Module 07 exercises
# This script validates that all exercises can run properly

set -e  # Exit on error

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

echo -e "${BLUE}🧪 Testing Module 07 Exercises${NC}"
echo "=================================="

# Function to test if a port is in use
check_port() {
    if lsof -Pi :$1 -sTCP:LISTEN -t >/dev/null ; then
        return 0
    else
        return 1
    fi
}

# Function to wait for a service to be ready
wait_for_service() {
    local port=$1
    local service=$2
    local max_attempts=30
    local attempt=0
    
    echo -e "${YELLOW}Waiting for $service on port $port...${NC}"
    
    while ! check_port $port; do
        attempt=$((attempt+1))
        if [ $attempt -gt $max_attempts ]; then
            echo -e "${RED}❌ $service failed to start${NC}"
            return 1
        fi
        sleep 1
    done
    
    echo -e "${GREEN}✅ $service is ready${NC}"
    return 0
}

# Test Exercise 1: Todo App
test_exercise_1() {
    echo -e "\n${BLUE}Testing Exercise 1: Todo App${NC}"
    echo "----------------------------"
    
    # Test frontend
    if [ -d "exercises/exercise-1-todo/starter/frontend" ]; then
        echo -e "${YELLOW}Testing frontend setup...${NC}"
        cd exercises/exercise-1-todo/starter/frontend
        
        # Check if package.json exists
        if [ -f "package.json" ]; then
            echo -e "${GREEN}✅ package.json found${NC}"
        else
            echo -e "${RED}❌ package.json missing${NC}"
            return 1
        fi
        
        # Check if node_modules exists
        if [ -d "node_modules" ]; then
            echo -e "${GREEN}✅ Dependencies installed${NC}"
        else
            echo -e "${YELLOW}Installing dependencies...${NC}"
            npm install
        fi
        
        # Test build
        echo -e "${YELLOW}Testing build...${NC}"
        npm run build
        echo -e "${GREEN}✅ Frontend builds successfully${NC}"
        
        cd - > /dev/null
    else
        echo -e "${RED}❌ Frontend directory not found${NC}"
        return 1
    fi
    
    # Test backend
    if [ -d "exercises/exercise-1-todo/starter/backend" ]; then
        echo -e "${YELLOW}Testing backend setup...${NC}"
        cd exercises/exercise-1-todo/starter/backend
        
        # Check if requirements.txt exists
        if [ -f "requirements.txt" ]; then
            echo -e "${GREEN}✅ requirements.txt found${NC}"
        else
            echo -e "${RED}❌ requirements.txt missing${NC}"
            return 1
        fi
        
        # Check if venv exists
        if [ -d "venv" ]; then
            echo -e "${GREEN}✅ Virtual environment found${NC}"
        else
            echo -e "${YELLOW}Creating virtual environment...${NC}"
            python -m venv venv
        fi
        
        # Test Python syntax
        if [ -f "main.py" ]; then
            python -m py_compile main.py
            echo -e "${GREEN}✅ Backend syntax valid${NC}"
        else
            echo -e "${YELLOW}⚠️  main.py not found (starter file)${NC}"
        fi
        
        cd - > /dev/null
    else
        echo -e "${RED}❌ Backend directory not found${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ Exercise 1 structure valid${NC}"
}

# Test Exercise 2: Notes App
test_exercise_2() {
    echo -e "\n${BLUE}Testing Exercise 2: Notes App${NC}"
    echo "-----------------------------"
    
    if [ -d "exercises/exercise-2-notes/starter/frontend" ]; then
        cd exercises/exercise-2-notes/starter/frontend
        
        # Check dependencies
        if [ -f "package.json" ]; then
            echo -e "${GREEN}✅ package.json found${NC}"
            
            # Check for required packages
            if grep -q "@uiw/react-md-editor" package.json; then
                echo -e "${GREEN}✅ Markdown editor dependency found${NC}"
            else
                echo -e "${RED}❌ Missing markdown editor dependency${NC}"
            fi
            
            if grep -q "fuse.js" package.json; then
                echo -e "${GREEN}✅ Search library found${NC}"
            else
                echo -e "${RED}❌ Missing search library${NC}"
            fi
        fi
        
        # Test build
        if [ -d "node_modules" ]; then
            npm run build
            echo -e "${GREEN}✅ Frontend builds successfully${NC}"
        fi
        
        cd - > /dev/null
    else
        echo -e "${RED}❌ Frontend directory not found${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ Exercise 2 structure valid${NC}"
}

# Test Exercise 3: Recipe AI
test_exercise_3() {
    echo -e "\n${BLUE}Testing Exercise 3: Recipe AI${NC}"
    echo "-----------------------------"
    
    # Test frontend
    if [ -d "exercises/exercise-3-recipes/starter/frontend" ]; then
        cd exercises/exercise-3-recipes/starter/frontend
        
        if [ -f "package.json" ]; then
            echo -e "${GREEN}✅ Frontend package.json found${NC}"
        fi
        
        if [ -d "node_modules" ]; then
            npm run build
            echo -e "${GREEN}✅ Frontend builds successfully${NC}"
        fi
        
        cd - > /dev/null
    fi
    
    # Test backend
    if [ -d "exercises/exercise-3-recipes/starter/backend" ]; then
        cd exercises/exercise-3-recipes/starter/backend
        
        # Check for .env.example
        if [ -f ".env.example" ]; then
            echo -e "${GREEN}✅ .env.example found${NC}"
        else
            echo -e "${RED}❌ .env.example missing${NC}"
        fi
        
        # Check for OpenAI dependency
        if [ -f "requirements.txt" ] && grep -q "openai" requirements.txt; then
            echo -e "${GREEN}✅ OpenAI dependency found${NC}"
        else
            echo -e "${RED}❌ OpenAI dependency missing${NC}"
        fi
        
        cd - > /dev/null
    fi
    
    echo -e "${GREEN}✅ Exercise 3 structure valid${NC}"
}

# Test Codespaces configuration
test_codespaces() {
    echo -e "\n${BLUE}Testing Codespaces Configuration${NC}"
    echo "---------------------------------"
    
    if [ -f ".devcontainer/devcontainer.json" ]; then
        echo -e "${GREEN}✅ devcontainer.json found${NC}"
        
        # Validate JSON syntax
        if python -m json.tool .devcontainer/devcontainer.json > /dev/null 2>&1; then
            echo -e "${GREEN}✅ devcontainer.json is valid JSON${NC}"
        else
            echo -e "${RED}❌ devcontainer.json has invalid JSON${NC}"
        fi
    else
        echo -e "${RED}❌ devcontainer.json missing${NC}"
    fi
    
    if [ -f ".devcontainer/setup.sh" ]; then
        echo -e "${GREEN}✅ setup.sh found${NC}"
        
        # Check if executable
        if [ -x ".devcontainer/setup.sh" ]; then
            echo -e "${GREEN}✅ setup.sh is executable${NC}"
        else
            echo -e "${YELLOW}⚠️  setup.sh is not executable${NC}"
            chmod +x .devcontainer/setup.sh
        fi
    else
        echo -e "${RED}❌ setup.sh missing${NC}"
    fi
}

# Test documentation
test_documentation() {
    echo -e "\n${BLUE}Testing Documentation${NC}"
    echo "--------------------"
    
    local required_docs=(
        "README.md"
        "docs/best-practices.md"
        "docs/troubleshooting.md"
        "docs/architecture-diagrams.md"
        "resources/copilot-prompts.md"
        "resources/quick-reference.md"
    )
    
    for doc in "${required_docs[@]}"; do
        if [ -f "$doc" ]; then
            echo -e "${GREEN}✅ $doc found${NC}"
        else
            echo -e "${RED}❌ $doc missing${NC}"
        fi
    done
}

# Main test execution
main() {
    echo -e "${BLUE}Starting Module 07 validation...${NC}\n"
    
    # Check if we're in the right directory
    if [ ! -f "README.md" ] || [ ! -d "exercises" ]; then
        echo -e "${RED}❌ Error: Must run from module-07 root directory${NC}"
        exit 1
    fi
    
    # Run all tests
    test_codespaces
    test_documentation
    test_exercise_1
    test_exercise_2
    test_exercise_3
    
    echo -e "\n${GREEN}=================================="
    echo -e "✅ All tests completed!"
    echo -e "==================================${NC}"
    echo ""
    echo "Module 07 is ready for students!"
    echo ""
    echo -e "${YELLOW}Next steps:${NC}"
    echo "1. Commit all changes"
    echo "2. Push to GitHub"
    echo "3. Test creating a Codespace"
    echo "4. Share repository with students"
}

# Run main function
main