"""
scrylo/api/app.py
------------------
FastAPI application factory — updated Week 2.
Adds: web UI router (HTMX pages), static files mount.
"""

from __future__ import annotations

import pathlib
from contextlib import asynccontextmanager

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

from scrylo.core.config import settings
from scrylo.db.session import init_db

STATIC_DIR = pathlib.Path(__file__).parent.parent / "web" / "static"


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_db()
    yield


def create_app() -> FastAPI:
    app = FastAPI(
        title="Scrylo",
        description="Local AI lead gen — no cloud, no subscriptions, no GPU",
        version=settings["app"]["version"],
        lifespan=lifespan,
        docs_url="/docs",
        redoc_url=None,
    )

    app.add_middleware(
        CORSMiddleware,
        allow_origins=[
            f"http://127.0.0.1:{settings['app']['port']}",
            f"http://localhost:{settings['app']['port']}",
        ],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # ── Static files ──────────────────────────────────────────
    if STATIC_DIR.exists():
        app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")

    # ── Routers ───────────────────────────────────────────────
    from scrylo.api.routers import health, leads, web
    app.include_router(health.router)
    app.include_router(leads.router, prefix="/api")
    app.include_router(web.router)          # Week 2 — HTMX pages

    return app


app = create_app()
