from __future__ import annotations

from src.integrations.exchange.models import BalanceSummary


def _safe_float(value: object, default: float = 0.0) -> float:
    try:
        return float(str(value))
    except (TypeError, ValueError):
        return default


def parse_account_balances(payload: dict) -> list[BalanceSummary]:
    # expected shapes seen in real APIs vary a lot
    # support:
    # 1) {"balances": [...]}
    # 2) {"payload": {"balances": [...]}}
    # 3) {"payload": [...]}
    # 4) {"assets": [...]}

    balances_raw = None

    if isinstance(payload.get("balances"), list):
        balances_raw = payload["balances"]
    else:
        inner = payload.get("payload")
        if isinstance(inner, dict) and isinstance(inner.get("balances"), list):
            balances_raw = inner["balances"]
        elif isinstance(inner, list):
            balances_raw = inner
        elif isinstance(payload.get("assets"), list):
            balances_raw = payload["assets"]

    if not isinstance(balances_raw, list):
        return []

    items: list[BalanceSummary] = []

    for item in balances_raw:
        if not isinstance(item, dict):
            continue

        currency = (
            str(item.get("asset") or item.get("currency") or item.get("code") or "")
            .strip()
            .upper()
        )
        if not currency:
            continue

        available = _safe_float(
            item.get("free", item.get("available", item.get("amount", 0.0)))
        )
        locked = _safe_float(
            item.get("locked", item.get("hold", item.get("reserved", 0.0)))
        )

        items.append(
            BalanceSummary(
                currency=currency,
                available=available,
                locked=locked,
                source="dzengi-private-api",
            )
        )

    return items
