"""Queue Position Modeling pipeline functions.

Pipeline functions:
    queue_tracker - Track queue position and fill probability
"""

from __future__ import annotations

from typing import Any, Callable

from horizon._horizon import QueueModel
from horizon.context import Context


def queue_tracker(
    feed: str,
    initial_queue: float = 100.0,
    orders_ahead: float = 50.0,
) -> Callable[[Context], dict[str, Any]]:
    """Create a queue position tracking pipeline function.

    Monitors orderbook queue dynamics and estimates fill probability
    for passive limit orders.

    Args:
        feed: Feed name to read book data from.
        initial_queue: Initial queue size estimate.
        orders_ahead: Initial orders ahead estimate.

    Returns:
        Pipeline function: (Context) -> dict with keys:
            fill_probability, expected_fill_time, queue_position,
            arrival_rate, cancel_rate
    """
    from horizon._horizon import auth_require_ultra
    auth_require_ultra()

    models: dict[str, QueueModel] = {}

    def _queue_tracker(ctx: Context) -> dict[str, Any]:
        market_id = ctx.market.id if ctx.market else "__default__"

        if market_id not in models:
            models[market_id] = QueueModel(initial_queue, orders_ahead)

        model = models[market_id]

        result = {
            "fill_probability": model.fill_probability(60.0),
            "expected_fill_time": model.expected_fill_time(),
            "queue_position": model.queue_position(),
            "arrival_rate": model.arrival_rate(),
            "cancel_rate": model.cancel_rate(),
        }

        return result

    _queue_tracker.__name__ = "queue_tracker"
    return _queue_tracker
