"""
cortex/api/routes/__init__.py — Router registration.

Collects all route modules and provides ``register_routes(app, verify_api_key)``
to mount them onto the FastAPI application.

Each call creates fresh APIRouter instances to avoid stale closures when
``create_app`` is called multiple times (e.g. in tests with different
API keys).
"""

from fastapi import APIRouter


def register_routes(app, verify_api_key):
    """Initialise all route modules and include their routers on *app*.

    Creates fresh APIRouter instances for each module to avoid leaking
    route registrations across multiple ``create_app`` calls.
    """
    from cortex.api.routes import (
        admin,
        brain_graph,
        commitments,
        config,
        config_routes,
        context,
        contradictions,
        cornerstones,
        dialectic,
        entities,
        events,
        export_import,
        graph,
        llm,
        memory,
        peers,
        sessions,
        stats,
    )

    _ROUTE_MODULES = [
        admin,
        memory,
        dialectic,
        cornerstones,
        entities,
        sessions,
        stats,
        events,
        config,
        config_routes,
        export_import,
        brain_graph,
        peers,
        graph,
        commitments,
        llm,
        context,
        contradictions,
    ]

    for mod in _ROUTE_MODULES:
        # Replace module-level router with a fresh instance
        mod.router = APIRouter()
        mod._make_routes(verify_api_key)
        app.include_router(mod.router)

    # Webhook routes (auth-gated via _make_routes, same pattern as above)
    from cortex.api.routes import webhooks
    webhooks.router = APIRouter()
    webhooks._make_routes(verify_api_key)
    app.include_router(webhooks.router)

    # Debug routes (diagnostic endpoints — auth-gated, always registered so
    # the clear-log audit trail is reachable; endpoints self-disable when
    # CORTEX_DEBUG=0 / debug logging is off)
    from cortex.api.routes import debug as debug_routes
    debug_routes.router = APIRouter()
    debug_routes._make_routes(verify_api_key)
    app.include_router(debug_routes.router)
