"""Runtime router construction from resolved build plans."""

from __future__ import annotations

from collections.abc import Callable

from fastapi import APIRouter

from auen._async_endpoints import (
    add_async_bulk_create,
    add_async_bulk_delete,
    add_async_bulk_update,
    add_async_create,
    add_async_delete,
    add_async_list,
    add_async_nested_create,
    add_async_nested_update,
    add_async_read,
    add_async_update,
)
from auen._endpoints import RouterContext
from auen.config import Operation
from auen.router_plan import RouterBuildPlan
from auen.types import SessionDep

_OP_BUILDERS = {
    Operation.CREATE: add_async_create,
    Operation.NESTED_CREATE: add_async_nested_create,
    Operation.LIST: add_async_list,
    Operation.READ: add_async_read,
    Operation.UPDATE: add_async_update,
    Operation.NESTED_UPDATE: add_async_nested_update,
    Operation.DELETE: add_async_delete,
    Operation.BULK_CREATE: add_async_bulk_create,
    Operation.BULK_UPDATE: add_async_bulk_update,
    Operation.BULK_DELETE: add_async_bulk_delete,
}


def build_router_from_plan(
    *,
    plan: RouterBuildPlan,
    session_dep: Callable[..., SessionDep],
) -> APIRouter:
    """Construct an APIRouter from an immutable router build plan."""
    router = APIRouter(prefix=plan.prefix, tags=list(plan.tags))

    ctx = RouterContext(
        router=router,
        model=plan.model,
        model_name=plan.model_name,
        schemas=plan.schemas,
        policy=plan.policy,
        session_dep=session_dep,
        auth=plan.auth,
        pk_name=plan.pk_name,
        pk_type=plan.pk_type,
        pagination=plan.pagination,
        filters=plan.filters,
        repository_factory=plan.repository_factory,
        hooks=plan.hooks,
        nested_writes=plan.nested_writes,
        nested_policy_registry=plan.nested_policy_registry,
        include_in_schema=plan.include_in_schema,
        operation_id_prefix=plan.operation_id_prefix,
    )

    for op, builder in _OP_BUILDERS.items():
        if op in plan.operations:
            builder(ctx)
    return router
