"""Parser for Crypto PnL (pnl.json)."""
from ..model import UnifiedTrade, BotSummary


def parse_crypto_pnl(data):
    """Parse crypto PnL trades.

    Schema: {trades: [{id, orderId, time, side, price, qty}],
             summary: {total_pnl, ...}}
    """
    trades = []
    raw = data.get("trades", [])

    # Match buy/sell pairs into round-trip trades
    buys = [t for t in raw if t.get("side", "").upper() == "BUY"]
    sells = [t for t in raw if t.get("side", "").upper() == "SELL"]

    for i, sell in enumerate(sells):
        buy = buys[i] if i < len(buys) else None
        if buy:
            buy_price = float(buy.get("price", 0))
            sell_price = float(sell.get("price", 0))
            qty = float(sell.get("qty", 0))
            if buy_price > 0:
                pnl_pct = ((sell_price - buy_price) / buy_price) * 100
            else:
                pnl_pct = 0
            trades.append(UnifiedTrade(
                bot="Crypto (MEXC)",
                asset="XRP/USDT",
                direction="LONG",
                entry_price=buy_price,
                exit_price=sell_price,
                pnl_pct=pnl_pct,
                entry_time=buy.get("time", ""),
                exit_time=sell.get("time", ""),
            ))

    return BotSummary(name="Crypto (MEXC)", trades=trades)
