"""Polymarket historical order book starter.

Use this file with the sample CSV from:
https://polyhistorical.com/datasets/polyhistorical-polymarket-orderbook-sample.csv

Then replace SAMPLE_CSV with an export from PolyHistorical or fetch live API
responses from https://api.polyhistorical.com/v1.
"""

from __future__ import annotations

import csv
from dataclasses import dataclass
from pathlib import Path
from statistics import mean


SAMPLE_CSV = Path("polyhistorical-polymarket-orderbook-sample.csv")


@dataclass(frozen=True)
class SnapshotRow:
    timestamp: str
    market_slug: str
    asset: str
    market_type: str
    token_side: str
    reference_price: float
    best_bid: float
    best_ask: float
    spread: float
    mid_price: float
    bid_depth_1pct: float
    ask_depth_1pct: float
    total_bid_depth: float
    total_ask_depth: float


def load_rows(path: Path) -> list[SnapshotRow]:
    with path.open(newline="", encoding="utf-8") as handle:
        reader = csv.DictReader(handle)
        return [
            SnapshotRow(
                timestamp=row["timestamp"],
                market_slug=row["market_slug"],
                asset=row["asset"],
                market_type=row["market_type"],
                token_side=row["token_side"],
                reference_price=float(row["reference_price"]),
                best_bid=float(row["best_bid"]),
                best_ask=float(row["best_ask"]),
                spread=float(row["spread"]),
                mid_price=float(row["mid_price"]),
                bid_depth_1pct=float(row["bid_depth_1pct"]),
                ask_depth_1pct=float(row["ask_depth_1pct"]),
                total_bid_depth=float(row["total_bid_depth"]),
                total_ask_depth=float(row["total_ask_depth"]),
            )
            for row in reader
        ]


def summarize(rows: list[SnapshotRow]) -> None:
    by_side: dict[str, list[SnapshotRow]] = {}
    for row in rows:
        by_side.setdefault(row.token_side, []).append(row)

    for side, side_rows in sorted(by_side.items()):
        average_spread = mean(row.spread for row in side_rows)
        average_mid = mean(row.mid_price for row in side_rows)
        average_depth = mean(row.bid_depth_1pct + row.ask_depth_1pct for row in side_rows)
        print(f"{side}: avg_spread={average_spread:.4f} avg_mid={average_mid:.4f} avg_1pct_depth={average_depth:.2f}")


if __name__ == "__main__":
    rows = load_rows(SAMPLE_CSV)
    summarize(rows)
