"""Jita market price provider (ESI-direct, public — no token).

Prices follow Janice's method: at Jita 4-4, JSV is the lowest sell order and
JBV is the highest buy order (best of book, station-filtered). Best-of-book on
buy naturally ignores the tail of 1-ISK bids that poison a volume percentile.

Swappable: only `jita_prices(type_id)` is consumed elsewhere, so an alternative
source (e.g. Fuzzwork) can replace the internals later.
"""

from functools import lru_cache

REGION_THE_FORGE = 10000002
JITA_44_STATION = 60003760  # Jita IV - Moon 4 - Caldari Navy Assembly Plant
COMPATIBILITY_DATE = "2025-12-16"  # ESI X-Compatibility-Date this client is tested against


@lru_cache(maxsize=1)
def _esi():
    """Lazily build the ESI client (avoids a spec download at import time)."""
    from esi.openapi_clients import ESIClientProvider

    from . import __version__

    return ESIClientProvider(
        compatibility_date=COMPATIBILITY_DATE,
        ua_appname="aa-shop",
        ua_version=__version__,
        operations=["GetMarketsRegionIdOrders"],
    )


def _field(order, name):
    """Read a field from an ESI order, tolerant of dict or attribute-object form."""
    return order[name] if isinstance(order, dict) else getattr(order, name)


def best_price(orders, is_buy: bool):
    """Best-of-book price for one side: highest buy / lowest sell.

    `orders`: list of orders (dict or object) with a `price`, one side only.
    Returns an int price, or None when there are no orders.
    """
    if not orders:
        return None
    prices = [_field(o, "price") for o in orders]
    return int(max(prices) if is_buy else min(prices))


def _fetch_orders(type_id: int):
    """All active market orders for a type in The Forge (public ESI, paginated).

    use_etag=False: market orders change constantly, and .results() raises
    HTTPNotModified on a 304 ETag hit rather than returning cached data.
    """
    return _esi().client.Market.GetMarketsRegionIdOrders(
        region_id=REGION_THE_FORGE, type_id=type_id, order_type="all"
    ).results(use_etag=False)


def jita_prices(type_id: int) -> dict:
    """{"buy": int|None, "sell": int|None} best-of-book prices at Jita 4-4."""
    orders = [
        o for o in _fetch_orders(type_id)
        if _field(o, "location_id") == JITA_44_STATION
    ]
    buys = [o for o in orders if _field(o, "is_buy_order")]
    sells = [o for o in orders if not _field(o, "is_buy_order")]
    return {
        "buy": best_price(buys, is_buy=True),
        "sell": best_price(sells, is_buy=False),
    }
