#!/bin/bash

# Module 21: AI Agents - Setup Script
# This script sets up the complete environment for Module 21

set -e  # Exit on error

echo "🚀 Setting up Module 21: Introduction to AI Agents"
echo "================================================"

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}✓${NC} $1"
}

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

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

# Check Python version
echo "📋 Checking prerequisites..."

python_version=$(python3 --version 2>&1 | awk '{print $2}')
required_version="3.11"

if [ "$(printf '%s\n' "$required_version" "$python_version" | sort -V | head -n1)" = "$required_version" ]; then 
    print_status "Python version $python_version meets requirement (>= $required_version)"
else
    print_error "Python version $python_version is below required version $required_version"
    exit 1
fi

# Check if virtual environment exists
if [ -d "venv" ]; then
    print_warning "Virtual environment already exists. Activating..."
else
    echo "🔧 Creating virtual environment..."
    python3 -m venv venv
    print_status "Virtual environment created"
fi

# Activate virtual environment
echo "🔌 Activating virtual environment..."
source venv/bin/activate || . venv/Scripts/activate

# Upgrade pip
echo "📦 Upgrading pip..."
pip install --upgrade pip setuptools wheel

# Install requirements
echo "📚 Installing required packages..."
cat > requirements.txt << EOF
# Core packages
aiohttp>=3.9.0
asyncio>=3.11.0
pydantic>=2.5.0
python-dotenv>=1.0.0

# AI/ML packages
openai>=1.10.0
langchain>=0.1.0
semantic-kernel>=0.5.0

# Development tools
pytest>=7.4.0
pytest-asyncio>=0.21.0
pytest-cov>=4.1.0
black>=23.0.0
mypy>=1.7.0
flake8>=6.1.0

# Monitoring
prometheus-client>=0.19.0
structlog>=23.2.0

# Additional tools
requests>=2.31.0
PyYAML>=6.0.1
click>=8.1.7
rich>=13.7.0
EOF

pip install -r requirements.txt
print_status "All packages installed"

# Create project structure
echo "📁 Creating project structure..."

directories=(
    "src"
    "src/agents"
    "src/operations"
    "src/tools"
    "src/config"
    "tests"
    "tests/unit"
    "tests/integration"
    "examples"
    "examples/sample_data"
    "docs"
    "scripts"
    "logs"
    ".github"
    ".github/workflows"
)

for dir in "${directories[@]}"; do
    mkdir -p "$dir"
    touch "$dir/__init__.py" 2>/dev/null || true
done

print_status "Project structure created"

# Create configuration files
echo "⚙️ Creating configuration files..."

# Create .env.example
cat > .env.example << EOF
# Azure Configuration
AZURE_SUBSCRIPTION_ID=your-subscription-id
AZURE_RESOURCE_GROUP=rg-ai-agents
AZURE_KEY_VAULT_NAME=kv-ai-agents

# OpenAI Configuration
OPENAI_API_KEY=your-api-key
OPENAI_API_ENDPOINT=https://api.openai.com/v1

# Agent Configuration
AGENT_LOG_LEVEL=INFO
AGENT_MAX_RETRIES=3
AGENT_TIMEOUT_SECONDS=30

# GitHub Configuration
GITHUB_TOKEN=your-github-token
GITHUB_REPO=your-username/your-repo
EOF

# Create .gitignore
cat > .gitignore << EOF
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
venv/
env/
ENV/

# Testing
.coverage
.pytest_cache/
htmlcov/
.tox/
.mypy_cache/

# IDE
.vscode/
.idea/
*.swp
*.swo

# Environment
.env
.env.local

# Logs
logs/
*.log

# OS
.DS_Store
Thumbs.db

# Build
build/
dist/
*.egg-info/
EOF

# Create setup.py
cat > setup.py << EOF
from setuptools import setup, find_packages

setup(
    name="ai-agents-module21",
    version="0.1.0",
    packages=find_packages(where="src"),
    package_dir={"": "src"},
    python_requires=">=3.11",
    install_requires=[
        line.strip()
        for line in open("requirements.txt")
        if not line.startswith("#") and line.strip()
    ],
    author="Your Name",
    author_email="your.email@example.com",
    description="Module 21: Introduction to AI Agents",
    long_description=open("README.md").read(),
    long_description_content_type="text/markdown",
    url="https://github.com/yourusername/module21-ai-agents",
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.11",
    ],
)
EOF

print_status "Configuration files created"

# Create sample base agent
echo "🤖 Creating sample agent code..."

cat > src/agents/base_agent.py << 'EOF'
"""Base agent class for all AI agents"""

from abc import ABC, abstractmethod
from typing import List, Dict, Any, Optional
import logging
from dataclasses import dataclass

@dataclass
class AgentConfig:
    """Configuration for agents"""
    name: str
    version: str = "1.0.0"
    max_retries: int = 3
    timeout_seconds: int = 30
    log_level: str = "INFO"

class BaseAgent(ABC):
    """Abstract base class for AI agents"""
    
    def __init__(self, config: AgentConfig):
        self.config = config
        self.logger = logging.getLogger(f"agent.{config.name}")
        self.logger.setLevel(config.log_level)
        self._initialize()
    
    @abstractmethod
    def _initialize(self) -> None:
        """Initialize agent-specific components"""
        pass
    
    @abstractmethod
    def process(self, input_data: Any) -> Any:
        """Process input and return result"""
        pass
    
    def health_check(self) -> Dict[str, Any]:
        """Check agent health status"""
        return {
            "status": "healthy",
            "name": self.config.name,
            "version": self.config.version
        }
EOF

# Create validation script
echo "✅ Creating validation script..."

cat > scripts/validate_setup.py << 'EOF'
#!/usr/bin/env python3
"""Validate Module 21 setup"""

import sys
import importlib
import subprocess
from pathlib import Path

def check_python_version():
    """Check Python version"""
    version = sys.version_info
    if version.major == 3 and version.minor >= 11:
        return True, f"Python {version.major}.{version.minor}.{version.micro}"
    return False, f"Python {version.major}.{version.minor}.{version.micro} (requires >= 3.11)"

def check_package(package_name):
    """Check if package is installed"""
    try:
        importlib.import_module(package_name)
        return True, "Installed"
    except ImportError:
        return False, "Not installed"

def check_azure_cli():
    """Check Azure CLI installation"""
    try:
        result = subprocess.run(["az", "--version"], capture_output=True, text=True)
        if result.returncode == 0:
            return True, "Installed"
    except FileNotFoundError:
        pass
    return False, "Not installed"

def check_project_structure():
    """Check project structure"""
    required_dirs = ["src", "tests", "examples", "docs", "scripts"]
    missing = [d for d in required_dirs if not Path(d).exists()]
    if missing:
        return False, f"Missing directories: {', '.join(missing)}"
    return True, "Complete"

def main():
    """Run all checks"""
    print("🔍 Validating Module 21 Setup")
    print("=" * 40)
    
    checks = [
        ("Python Version", check_python_version),
        ("Project Structure", check_project_structure),
        ("OpenAI Package", lambda: check_package("openai")),
        ("Pytest Package", lambda: check_package("pytest")),
        ("Azure CLI", check_azure_cli),
    ]
    
    all_passed = True
    
    for name, check_func in checks:
        passed, message = check_func()
        status = "✅" if passed else "❌"
        print(f"{status} {name}: {message}")
        if not passed:
            all_passed = False
    
    print("=" * 40)
    
    if all_passed:
        print("✅ All checks passed! You're ready to start Module 21.")
        return 0
    else:
        print("❌ Some checks failed. Please fix the issues above.")
        return 1

if __name__ == "__main__":
    sys.exit(main())
EOF

chmod +x scripts/validate_setup.py

# Create Azure setup script
echo "☁️ Creating Azure setup script..."

cat > scripts/setup_azure_resources.sh << 'EOF'
#!/bin/bash

# Azure resource setup for Module 21

set -e

# Load environment variables
if [ -f .env ]; then
    export $(cat .env | grep -v '^#' | xargs)
fi

echo "🔧 Setting up Azure resources for Module 21..."

# Variables
RESOURCE_GROUP=${AZURE_RESOURCE_GROUP:-"rg-ai-agents-module21"}
LOCATION=${AZURE_LOCATION:-"eastus"}
KEY_VAULT_NAME=${AZURE_KEY_VAULT_NAME:-"kv-agents-$RANDOM"}
STORAGE_ACCOUNT="stagents$RANDOM"

# Create resource group
echo "Creating resource group..."
az group create --name $RESOURCE_GROUP --location $LOCATION

# Create Key Vault
echo "Creating Key Vault..."
az keyvault create \
    --name $KEY_VAULT_NAME \
    --resource-group $RESOURCE_GROUP \
    --location $LOCATION

# Create storage account
echo "Creating storage account..."
az storage account create \
    --name $STORAGE_ACCOUNT \
    --resource-group $RESOURCE_GROUP \
    --location $LOCATION \
    --sku Standard_LRS

# Create Application Insights
echo "Creating Application Insights..."
az monitor app-insights component create \
    --app ai-agents-module21 \
    --location $LOCATION \
    --resource-group $RESOURCE_GROUP

echo "✅ Azure resources created successfully!"
echo "Resource Group: $RESOURCE_GROUP"
echo "Key Vault: $KEY_VAULT_NAME"
echo "Storage Account: $STORAGE_ACCOUNT"
EOF

chmod +x scripts/setup_azure_resources.sh

# Run validation
echo "🔍 Running validation..."
python scripts/validate_setup.py

echo ""
echo "🎉 Module 21 setup complete!"
echo ""
echo "Next steps:"
echo "1. Copy .env.example to .env and fill in your values"
echo "2. Run 'source venv/bin/activate' to activate the virtual environment"
echo "3. Run './scripts/setup_azure_resources.sh' to create Azure resources (optional)"
echo "4. Start with the first exercise in exercises/exercise1-easy/"
echo ""
echo "Happy coding! 🚀"