"""The FastAPI app factory — mount the brand kit, wire Jinja, register the routes.

``create_app()`` builds the ASGI app: the shared ``mgf-brand-web`` static kit at
``/static/brand`` (one source of truth for Magogi styling + the operator-instrument
layer), the app's own shell ``app.css`` at ``/static``, the Jinja templates, and the
read-mostly console routes. ``roots`` (optional) pins which project dirs the console
shows — tests pass an explicit list; production discovers them from the environment.
"""

from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from mgf.brand_web import static_dir as brand_static_dir
from mgf.brand_web import templates_dir as brand_templates_dir

from .routes import build_router

if TYPE_CHECKING:
    from collections.abc import Sequence

_HERE = Path(__file__).parent
_TEMPLATES = _HERE / "templates"
_STATIC = _HERE / "static"


def create_app(roots: Sequence[str | Path] | None = None) -> FastAPI:
    """Build the ProofWarden console (read-mostly; binds localhost in ``__main__``)."""
    app = FastAPI(title="ProofWarden — mgf-test-web", docs_url=None, redoc_url=None)
    # Mount the brand kit FIRST so its more-specific /static/brand prefix wins over
    # the app's own /static mount (which carries only the app-domain app.css —
    # the console shell itself is the kit's).
    app.mount("/static/brand", StaticFiles(directory=str(brand_static_dir())), name="brand")
    app.mount("/static", StaticFiles(directory=str(_STATIC)), name="static")

    # App templates first (they win name clashes), then the kit's template pack
    # (M1 P4.2): base.html extends "mgf/console.html" (the .mgf-console shell)
    # and macros.html re-exports "mgf/macros.html" (chips/absence/icons).
    templates = Jinja2Templates(directory=[str(_TEMPLATES), str(brand_templates_dir())])
    resolved = [Path(r) for r in roots] if roots is not None else None
    app.include_router(build_router(templates, resolved))
    return app
