"""Main FastAPI application for Claude Code Monitor."""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging
import time

from app.database import init_db
from app.api import events, statistics, websocket_endpoint
from app.schemas import HealthResponse

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


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan handler for startup and shutdown events."""
    # Startup
    logger.info("Starting Claude Code Monitor backend...")
    init_db()
    logger.info("Database initialized successfully")
    logger.info("Backend ready to receive events")
    yield
    # Shutdown
    logger.info("Shutting down Claude Code Monitor backend...")


# Create FastAPI app
app = FastAPI(
    title="Claude Code Monitor API",
    description="Real-time monitoring dashboard for Claude Code activity",
    version="1.0.0",
    lifespan=lifespan,
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # In production, specify exact origins
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(events.router)
app.include_router(statistics.router)
app.include_router(websocket_endpoint.router)


# Health check endpoint
@app.get("/health", response_model=HealthResponse, tags=["health"])
async def health_check():
    """
    Health check endpoint.

    Returns the service status and current timestamp.
    """
    return HealthResponse(status="healthy", timestamp=time.time())


# Root endpoint
@app.get("/", tags=["info"])
async def root():
    """Root endpoint with API information."""
    return {
        "name": "Claude Code Monitor API",
        "version": "1.0.0",
        "status": "running",
        "docs": "/docs",
        "websocket": "/ws",
    }


if __name__ == "__main__":
    import uvicorn

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