"""Offline synthetic example: compare reviewed displayed item-price samples."""
from decimal import Decimal, InvalidOperation
from statistics import median


def summarize(rows, population, included_ids, currency="USD"):
    field, currency_field = ("soldPrice", "soldCurrency") if population == "sold" else ("currentPrice", "currentCurrency")
    seen, amounts = set(), []
    for row in rows:
        item_id = row.get("itemId")
        if not item_id or item_id in seen:
            continue
        seen.add(item_id)
        if item_id not in included_ids or row.get("listingType") != population:
            continue
        if row.get(currency_field) != currency:
            continue
        if row.get("quality", {}).get("priceBasis") != "displayed_listing_price":
            continue
        try:
            amount = Decimal(str(row.get(field)))
        except (InvalidOperation, ValueError):
            continue
        if amount.is_finite() and amount >= 0:
            amounts.append(amount)
    return {"count": len(amounts), "median": median(amounts) if amounts else None}


def synthetic_row(item_id, population, amount, currency="USD", basis="displayed_listing_price"):
    field, currency_field = ("soldPrice", "soldCurrency") if population == "sold" else ("currentPrice", "currentCurrency")
    return {"itemId": item_id, "listingType": population, field: amount, currency_field: currency,
            "quality": {"priceBasis": basis, "acceptedOfferAmount": None,
                        "saleDateVerified": False, "exactProductMatchVerified": False}}


if __name__ == "__main__":
    active = [synthetic_row("A1", "active", "140.00"), synthetic_row("A2", "active", "150.00"),
              synthetic_row("A3", "active", "160.00"), synthetic_row("A2", "active", "150.00"),
              synthetic_row("AX", "active", "5.00"), synthetic_row("AE", "active", "99.00", "EUR")]
    sold = [synthetic_row("S1", "sold", "110.00"), synthetic_row("S2", "sold", "120.00"),
            synthetic_row("S3", "sold", "130.00"), synthetic_row("SR", "sold", "20.00", basis="range_lower_bound"),
            synthetic_row("SN", "sold", None)]
    a = summarize(active, "active", {"A1", "A2", "A3", "AE"})
    s = summarize(sold, "sold", {"S1", "S2", "S3", "SR", "SN"})
    assert a == {"count": 3, "median": Decimal("150.00")}
    assert s == {"count": 3, "median": Decimal("120.00")}
    assert summarize([], "sold", set()) == {"count": 0, "median": None}
    assert summarize([synthetic_row("I", "sold", "NaN")], "sold", {"I"})["count"] == 0
    assert summarize([synthetic_row("I", "sold", "-1")], "sold", {"I"})["count"] == 0
    assert summarize([synthetic_row("I", "active", "100")], "sold", {"I"})["count"] == 0
    print("SYNTHETIC EXAMPLE ONLY; amounts are not live market observations.")
    print(f"Active: n={a['count']}, displayed item-price median USD {a['median']:.2f}")
    print(f"Sold search: n={s['count']}, displayed item-price median USD {s['median']:.2f}")
    print(f"Displayed-sample difference: USD {a['median'] - s['median']:.2f}")
