"""FastAPI application for mosaic-coordinator webhook receiver."""

import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI
from pydantic import BaseModel

from .config import settings
from .webhook import router as webhook_router


# Configure logging
def setup_logging() -> None:
    """Configure logging for the application."""
    log_level = getattr(logging, settings.log_level.upper(), logging.INFO)
    logging.basicConfig(
        level=log_level,
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )


# Setup logging on module import
setup_logging()
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """
    Application lifespan manager.

    Handles startup and shutdown logic.
    """
    # Startup
    logger.info("Starting mosaic-coordinator webhook receiver")
    logger.info(f"Gitea URL: {settings.gitea_url}")
    logger.info(f"Log level: {settings.log_level}")
    logger.info(f"Server: {settings.host}:{settings.port}")

    yield

    # Shutdown
    logger.info("Shutting down mosaic-coordinator webhook receiver")


# Create FastAPI application
app = FastAPI(
    title="Mosaic Coordinator",
    description="Webhook receiver for Gitea issue events",
    version="0.0.1",
    lifespan=lifespan,
)


class HealthResponse(BaseModel):
    """Health check response model."""

    status: str
    service: str


@app.get("/health", response_model=HealthResponse)
async def health_check() -> HealthResponse:
    """
    Health check endpoint.

    Returns:
        HealthResponse indicating service is healthy
    """
    return HealthResponse(status="healthy", service="mosaic-coordinator")


# Include webhook router
app.include_router(webhook_router)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "src.main:app",
        host=settings.host,
        port=settings.port,
        reload=True,
        log_level=settings.log_level.lower(),
    )
