"""FastAPI application entry-point.

Creates the ASGI app, registers CORS middleware, includes all routers,
and provides a lifespan hook for startup / shutdown logic.
"""

import logging
from contextlib import asynccontextmanager

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

from app.config import settings

logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Handle application startup and shutdown events."""
    logger.info("Starting %s", settings.app_name)
    # ── startup tasks ────────────────────────────────────────────── #
    # e.g. initialise Redis pool, validate S3 connectivity, etc.
    yield
    # ── shutdown tasks ───────────────────────────────────────────── #
    logger.info("Shutting down %s", settings.app_name)


app = FastAPI(
    title=settings.app_name,
    version="0.1.0",
    lifespan=lifespan,
)

# ── CORS (permissive for development) ────────────────────────────── #
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_allow_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ── health check ─────────────────────────────────────────────────── #
@app.get("/health", tags=["system"])
def health_check():
    return {"status": "ok", "app": settings.app_name}


# ── routers ─────────────────────────────────────────────────────── #
from app.routers import (
    ai,
    auth,
    floors,
    hotspots,
    houses,
    panoramas,
    permissions,
    publish,
    rooms,
    upload,
    users,
)

app.include_router(auth.router, prefix="/api/auth", tags=["auth"])
app.include_router(users.router, prefix="/api/users", tags=["users"])
app.include_router(houses.router, prefix="/api/houses", tags=["houses"])
app.include_router(floors.router, tags=["floors"])
app.include_router(rooms.router, tags=["rooms"])
app.include_router(panoramas.router, tags=["panoramas"])
app.include_router(hotspots.router, tags=["hotspots"])
app.include_router(upload.router, prefix="/api/upload", tags=["upload"])
app.include_router(publish.router, tags=["publish"])
app.include_router(permissions.router, tags=["permissions"])
app.include_router(ai.router, tags=["ai"])


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.debug,
    )
