# Copy the content from the main_app_file artifact above
# src/main.py
"""
FastAPI application entry point for the self-improving code generator
"""

import logging
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from .utils.config import get_settings, validate_configuration
from .models.database_models import Base
from .api.routes import router
from .services.orchestrator import SelfImprovingCodeGenerator

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s"
)
logger = logging.getLogger(__name__)

# Global variables
generator: SelfImprovingCodeGenerator = None
engine = None
SessionLocal = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan events"""
    global generator, engine, SessionLocal
    
    try:
        # Validate configuration
        validate_configuration()
        settings = get_settings()
        
        logger.info("🚀 Starting Self-Improving Code Generator")
        
        # Initialize database
        engine = create_engine(settings.database_url)
        SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
        
        # Create database tables
        Base.metadata.create_all(bind=engine)
        logger.info("✅ Database initialized")
        
        # Initialize the generator
        generator = SelfImprovingCodeGenerator(
            claude_api_key=settings.claude_api_key,
            database_url=settings.database_url
        )
        logger.info("✅ Self-improving generator initialized")
        
        yield
        
    except Exception as e:
        logger.error(f"❌ Failed to start application: {e}")
        raise
    finally:
        logger.info("🛑 Shutting down Self-Improving Code Generator")

# Create FastAPI app
app = FastAPI(
    title="Self-Improving Code Generator",
    description="AI-powered code generation with continuous quality improvement",
    version="1.0.0",
    lifespan=lifespan
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure for your needs
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include API routes
app.include_router(router, prefix="/api/v1")

# Dependency to get generator instance
def get_generator() -> SelfImprovingCodeGenerator:
    """Get the global generator instance"""
    if generator is None:
        raise HTTPException(status_code=500, detail="Generator not initialized")
    return generator

# Dependency to get database session
def get_db():
    """Get database session"""
    if SessionLocal is None:
        raise HTTPException(status_code=500, detail="Database not initialized")
    
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "Self-Improving Code Generator",
        "version": "1.0.0",
        "status": "running",
        "capabilities": [
            "Technology-agnostic analysis",
            "Progressive enhancement",
            "Learning from user preferences",
            "Real-time improvement tracking",
            "Multi-language support"
        ]
    }

@app.get("/health")
async def health_check():
    """Health check endpoint"""
    settings = get_settings()
    
    health_status = {
        "status": "healthy",
        "service": "Self-Improving Code Generator",
        "version": "1.0.0",
        "timestamp": "2024-01-01T00:00:00Z",
        "dependencies": {
            "database": "connected" if engine else "disconnected",
            "claude_api": "configured" if settings.claude_api_key else "not_configured",
            "generator": "initialized" if generator else "not_initialized"
        }
    }
    
    # Check if all dependencies are healthy
    all_healthy = all(
        status == "connected" or status == "configured" or status == "initialized"
        for status in health_status["dependencies"].values()
    )
    
    if not all_healthy:
        health_status["status"] = "unhealthy"
    
    return health_status

if __name__ == "__main__":
    import uvicorn
    settings = get_settings()
    
    uvicorn.run(
        "src.main:app",
        host=settings.service_host,
        port=settings.service_port,
        reload=True,
        log_level=settings.log_level.lower()
    )