"""洋葱组装(D1): 把中间件序列外→内绑定到终端调用上。"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from collections.abc import Sequence

    from polygateway.ports import CallNext, Middleware


def compose(middlewares: Sequence[Middleware], terminal: CallNext) -> CallNext:
    """外→内绑定: compose([A, B], t) 的调用序为 A → B → t。"""
    handler = terminal
    for mw in reversed(middlewares):
        handler = _bind(mw, handler)
    return handler


def _bind(mw: Middleware, nxt: CallNext) -> CallNext:
    async def call(request):
        return await mw(request, nxt)

    return call
