from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
from typing import Dict, Any

from .endpoints import optimization, analytics, models
from ..analytics.performance import PerformanceAnalyzer
from ..analytics.regime import RegimeDetector
from ..optimization.portfolio_optimizer import PortfolioOptimizer

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Global instances
performance_analyzer = PerformanceAnalyzer()
regime_detector = RegimeDetector()
portfolio_optimizer = PortfolioOptimizer()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    logger.info("Starting Trading Analytics Service...")
    # Initialize connections, load models, etc.
    yield
    # Shutdown
    logger.info("Shutting down Trading Analytics Service...")

# Create FastAPI app
app = FastAPI(
    title="Trading Analytics Service",
    description="Complex analytics, optimization, and ML inference for trading",
    version="0.1.0",
    lifespan=lifespan
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure appropriately for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(optimization.router, prefix="/optimize", tags=["optimization"])
app.include_router(analytics.router, prefix="/analytics", tags=["analytics"])
app.include_router(models.router, prefix="/models", tags=["models"])

@app.get("/")
async def root():
    return {
        "service": "Trading Analytics",
        "status": "operational",
        "version": "0.1.0"
    }

@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "components": {
            "performance_analyzer": "operational",
            "regime_detector": "operational",
            "portfolio_optimizer": "operational"
        }
    }

# Dependency injection
def get_performance_analyzer():
    return performance_analyzer

def get_regime_detector():
    return regime_detector

def get_portfolio_optimizer():
    return portfolio_optimizer