from fastapi import FastAPI, Request
from contextlib import asynccontextmanager
from fastapi.middleware.cors import CORSMiddleware
import sys
import logging
import os

# Add shared modules to path
sys.path.append('/app')

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

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    # Startup
    logger.info("Starting Auth Service...")
    
    try:
        # Initialize database
        from shared.database import connect_to_mongo, init_database
        from app.models import User, AuthSession, RefreshToken
        
        await connect_to_mongo()
        await init_database([User, AuthSession, RefreshToken])
        
        # Connect to Redis
        from shared.redis_client import redis_client
        await redis_client.connect()
        
        # Initialize HTTP client
        from shared.http_client import http_client
        await http_client.connect()
        
        logger.info("Auth Service started successfully")
        
    except Exception as e:
        logger.error(f"Failed to start Auth Service: {e}")
        raise
    
    yield
    
    # Shutdown
    logger.info("Shutting down Auth Service...")
    
    try:
        # Close database connection
        from shared.database import close_mongo_connection
        await close_mongo_connection()
        
        # Close Redis connection
        from shared.redis_client import redis_client
        await redis_client.disconnect()
        
        # Close HTTP client
        from shared.http_client import http_client
        await http_client.disconnect()
        
        # Close Kafka producer
        from shared.kafka_client import kafka_client
        kafka_client.close_producer()
        
        logger.info("Auth Service shut down successfully")
        
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")

# Create FastAPI application
app = FastAPI(
    title="Mana Pige Auth Service",
    description="Authentication and authorization service for Mana Pige platform",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

origins = [
    "http://localhost",
    "http://localhost:3000",  # React or Vue dev server
    "http://mana_pige_frontend"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,           # Allowed origins
    allow_credentials=True,          # Allow cookies/auth headers
    allow_methods=["*"],              # Allow all HTTP methods (GET, POST, PUT, DELETE, etc.)
    allow_headers=["*"],              # Allow all headers
)

# Add middleware
from app.core.middleware import (
    add_cors_middleware,
    add_rate_limiting_middleware,
    log_requests_middleware,
    security_headers_middleware
)

add_cors_middleware(app)
add_rate_limiting_middleware(app)

# Add custom middleware
app.middleware("http")(log_requests_middleware)
app.middleware("http")(security_headers_middleware)

# Include API routers
from app.api.v1 import auth_router, users_router, tokens_router

app.include_router(auth_router, prefix="/api/v1")
app.include_router(users_router, prefix="/api/v1")
app.include_router(tokens_router, prefix="/api/v1")

# Root endpoint
@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "Mana Pige Auth Service",
        "version": "1.0.0",
        "status": "running",
        "docs": "/docs"
    }

# Health check endpoint
@app.get("/health")
async def health_check():
    """Health check endpoint"""
    try:
        # Check database connection
        from shared.database import mongodb
        if not mongodb.client:
            return {"status": "unhealthy", "reason": "database not connected"}
        
        # Check Redis connection
        from shared.redis_client import redis_client
        if not redis_client.redis:
            return {"status": "unhealthy", "reason": "redis not connected"}
        
        return {
            "status": "healthy",
            "service": "auth-service",
            "version": "1.0.0"
        }
        
    except Exception as e:
        return {
            "status": "unhealthy",
            "reason": str(e)
        }

# Error handlers
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """Global exception handler"""
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    
    return {
        "error": "Internal server error",
        "message": "An unexpected error occurred"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )
