"""Setup mode guard middleware.

Returns 503 for all non-setup API endpoints when the server is in setup mode
(no vault configured). Prevents AttributeError crashes from routes that access
app.state.agent / app.state.memory / etc. before services are initialized.
"""

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse

# Paths that are allowed during setup mode
_SETUP_ALLOWED = (  # arch:deterministic — route allowlist for setup mode, not strategy
    "/api/setup",
    "/api/health",
    "/api/settings/locale",
    "/api/onboarding",
    "/api/launch",
    "/api/systems",
)


class SetupGuardMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):  # type: ignore[override]
        if not getattr(request.app.state, "setup_mode", False):
            return await call_next(request)

        path = request.url.path

        # Allow setup-related endpoints, static files, and the SPA
        if any(path.startswith(p) for p in _SETUP_ALLOWED):
            return await call_next(request)

        # Allow non-API paths (static UI files, SPA fallback)
        if not path.startswith("/api/"):
            return await call_next(request)

        # Block all other API routes with a clear message
        return JSONResponse(
            status_code=503,
            content={
                "detail": "AgntSpace is not configured yet. Open http://localhost:8000 to set up your vault.",
                "setup_mode": True,
            },
        )
