# ai_mouse/server/__init__.py
"""AI Mouse server package — FastAPI app factory."""
from __future__ import annotations

import logging
from pathlib import Path

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

from .routes_collect import router as collect_router
from .routes_scroll import router as scroll_router
from .routes_train import router as train_router
from .routes_verify import router as verify_router

logger = logging.getLogger(__name__)

_HERE = Path(__file__).resolve().parent
_STATIC_DIR = _HERE.parent.parent / "static"


def create_app() -> FastAPI:
    """Create and configure the FastAPI application."""
    app = FastAPI(title="AI Mouse Trajectory Generator")

    # CORS — allow all origins (local development tool)
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Routers
    app.include_router(collect_router, prefix="/api")
    app.include_router(train_router, prefix="/api")
    app.include_router(verify_router, prefix="/api")
    app.include_router(scroll_router, prefix="/api/scroll")

    # Static files
    app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static")

    # Serve index.html at root
    @app.get("/")
    def index() -> FileResponse:
        return FileResponse(str(_STATIC_DIR / "index.html"))

    return app
