from __future__ import annotations

from pmls.api.gamma_client import extract_outcome_token_ids, fetch_market_by_slug
from pmls.credentials import public_client
from pmls.models import DisplayOutcome


def fetch_market_orderbooks(market_slug: str, depth: int = 3) -> list[DisplayOutcome]:
    market = fetch_market_by_slug(market_slug)
    outcome_tokens = extract_outcome_token_ids(market)
    client = public_client()

    snapshots: list[DisplayOutcome] = []
    for outcome, token_id in outcome_tokens.items():
        try:
            orderbook = client.get_order_book(token_id)
        except Exception as exc:
            raise RuntimeError(f"Failed to fetch CLOB orderbook for token {token_id}.") from exc

        asks = sorted(
            (item for item in orderbook.asks if item.price),
            key=lambda item: float(item.price),
        )[:depth][::-1]
        bids = sorted(
            (item for item in orderbook.bids if item.price),
            key=lambda item: float(item.price),
            reverse=True,
        )[:depth]
        snapshots.append(DisplayOutcome(outcome=outcome, token_id=token_id, asks=asks, bids=bids))

    return snapshots
