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

# 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("account_service")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan manager"""
    # Startup
    logger.info("Starting Account Service...")
    
    try:
        # Initialize database
        from shared.database import connect_to_mongo, init_database
        from app.models import UserProfile, Role, UserRole
        
        await connect_to_mongo()
        await init_database([UserProfile, Role, UserRole])  # Initialize all models
        # Ensure system roles (including default 'user') exist
        await Role.create_system_roles()
        
        # Connect to Redis
        from shared.redis_client import redis_client
        await redis_client.connect()
        
        # Start Kafka consumer in background
        from app.services.kafka_consumer import kafka_consumer
        consumer_task = asyncio.create_task(kafka_consumer.start_consuming())
        
        logger.info("Account Service started successfully")
        
    except Exception as e:
        logger.error(f"Failed to start Account Service: {e}")
        raise
    
    yield
    
    # Shutdown
    logger.info("Shutting down Account Service...")
    
    try:
        # Stop Kafka consumer
        from app.services.kafka_consumer import kafka_consumer
        kafka_consumer.stop_consuming()
        
        # 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()
        
        logger.info("Account Service shut down successfully")
        
    except Exception as e:
        logger.error(f"Error during shutdown: {e}")

# Create FastAPI application
app = FastAPI(
    title="Mana Pige Account Service",
    description="User profile, role, and permission management service for Mana Pige platform",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

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

add_cors_middleware(app)
add_rate_limiting_middleware(app)

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 custom middleware
app.middleware("http")(log_requests_middleware)
app.middleware("http")(security_headers_middleware)
app.middleware("http")(profile_access_middleware)

# Include API routers
from app.api.v1 import profiles_router
from app.api.roles import router as roles_router

app.include_router(profiles_router, prefix="/api/v1")
app.include_router(roles_router, prefix="/api/v1/accounts")

# Root endpoint
@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "Mana Pige Account 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": "account-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"
    )
