"""
Alert Processor API Server
Provides REST API endpoints for alert analytics
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import structlog

from app.config import AlertProcessorConfig
from app.api import analytics_router, alerts_router
from shared.database.base import create_database_manager

logger = structlog.get_logger()

# Create FastAPI app
app = FastAPI(
    title="Alert Processor API",
    description="API for alert analytics and interaction tracking",
    version="1.0.0"
)

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

# Include routers
app.include_router(analytics_router, tags=["analytics"])
app.include_router(alerts_router, tags=["alerts"])

# Initialize database
config = AlertProcessorConfig()
db_manager = create_database_manager(config.DATABASE_URL, "alert-processor-api")


@app.on_event("startup")
async def startup():
    """Initialize on startup"""
    logger.info("Alert Processor API starting up")

    # Create tables
    try:
        from app.models.alerts import Base
        await db_manager.create_tables(Base.metadata)
        logger.info("Database tables ensured")
    except Exception as e:
        logger.error("Failed to create tables", error=str(e))


@app.on_event("shutdown")
async def shutdown():
    """Cleanup on shutdown"""
    logger.info("Alert Processor API shutting down")
    await db_manager.close_connections()


@app.get("/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "service": "alert-processor-api"}


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "Alert Processor API",
        "version": "1.0.0",
        "endpoints": {
            "health": "/health",
            "docs": "/docs",
            "analytics": "/api/v1/tenants/{tenant_id}/alerts/analytics",
            "interactions": "/api/v1/tenants/{tenant_id}/alerts/{alert_id}/interactions"
        }
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8010)
