"""Compare real trade ticks with one-second last-trade prices.

Examples:
    python renko_resolution.py
    python renko_resolution.py --csv trades.csv --size 1 5 60

Local CSV columns: timestamp,trade_id,price. Timestamp is Unix seconds
in UTC, with optional decimals. Preserve exchange trade order.
"""
import argparse
import csv
import json
from collections import defaultdict
from datetime import datetime, timezone
from decimal import Decimal
from statistics import median
from urllib.request import urlopen

from renko_lab import Renko, number

START = 1796196169
END = 1796197160
FIRST_ID = 118947905
LAST_ID = 118948896
KRAKEN_URL = (
    "https://api.kraken.com/0/public/Trades?pair=XBTUSD&count=1000"
    f"&since={START * 1_000_000_000 - 1}"
)


def kraken_rows(body):
    response = json.loads(body, parse_float=Decimal)
    if response["error"]:
        raise ValueError(f'Kraken: {response["error"]}')
    data = next(value for key, value in response["result"].items() if key != "last")
    rows = [(Decimal(row[2]), int(row[6]), number(row[0])) for row in data
            if START <= row[2] < END]
    if [row[1] for row in rows] != list(range(FIRST_ID, LAST_ID + 1)):
        raise ValueError("The fixed Kraken sample is incomplete or out of order")
    return rows


def csv_rows(file):
    return [(number(row["timestamp"]), int(row["trade_id"]), number(row["price"]))
            for row in csv.DictReader(file)]


def seconds(rows):
    closing = {}
    for timestamp, _, price in rows:
        closing[int(timestamp)] = price
    return closing.items()


def outcomes(observations, anchor, size, fast, slow):
    builder = Renko(size)
    list(builder.update(anchor))
    a = b = None
    fast_weight = Decimal(2) / (fast + 1)
    slow_weight = Decimal(2) / (slow + 1)
    counts = {"bricks": 0, "reversals": 0, "ema": 0}
    direction = 0
    events = defaultdict(list)

    def event(kind, side):
        counts[kind] += 1
        events[(kind, bucket, side)].append(timestamp)

    for bucket, timestamp, price in observations:
        before = a - b if counts["bricks"] >= slow else None
        previous_count = counts["bricks"]
        for close, side in builder.update(price):
            if direction and direction != side:
                event("reversals", side)
            direction = side
            counts["bricks"] += 1
            a = close if a is None else a + fast_weight * (close - a)
            b = close if b is None else b + slow_weight * (close - b)
        if before is None or counts["bricks"] == previous_count:
            continue
        after = a - b
        if before <= 0 < after:
            event("ema", 1)
        elif before >= 0 > after:
            event("ema", -1)
    return counts, events


def match(tick_events, sampled_events, kind):
    delays = [(late - early) * 1000
              for key, series in tick_events.items() if key[0] == kind
              for early, late in zip(series, sampled_events.get(key, []))]
    return {"matched": len(delays),
            "median_delay_ms": round(float(median(delays)), 1) if delays else None}


def compare(rows, sizes, fast=5, slow=15):
    if len(rows) < 2:
        raise ValueError("At least two trades are required")
    if any(not t.is_finite() or t <= 0 for t, _, _ in rows):
        raise ValueError("Timestamps must be finite Unix seconds")
    if any(t2 < t1 or id2 <= id1 for (t1, id1, _), (t2, id2, _) in zip(rows, rows[1:])):
        raise ValueError("Expected increasing trade IDs and nondecreasing timestamps")
    anchor = rows[0][2]
    closes = [(bucket, Decimal(bucket + 1), value) for bucket, value in seconds(rows)]
    ticks = [(int(timestamp), timestamp, price) for timestamp, _, price in rows]
    metrics = []
    for size in sizes:
        direct, tick_events = outcomes(ticks, anchor, size, fast, slow)
        sampled, sampled_events = outcomes(closes, anchor, size, fast, slow)
        metrics.append({"size": str(size), "tick": direct, "second": sampled,
                        "matched_ema": match(tick_events, sampled_events, "ema"),
                        "matched_reversals": match(tick_events, sampled_events, "reversals")})
    return {"trades": len(rows), "quoted_seconds": len(closes), "ema_periods": [fast, slow],
            "first_trade_utc": datetime.fromtimestamp(float(rows[0][0]), timezone.utc).isoformat(),
            "last_trade_utc": datetime.fromtimestamp(float(rows[-1][0]), timezone.utc).isoformat(),
            "metrics": metrics}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--csv", help="Use a local CSV instead of the fixed public sample")
    parser.add_argument("--size", type=number, nargs="+", default=[Decimal(x) for x in (1, 2, 5, 10, 20, 60)])
    args = parser.parse_args()
    if args.csv:
        with open(args.csv, newline="", encoding="utf-8-sig") as file:
            rows = csv_rows(file)
    else:
        with urlopen(KRAKEN_URL, timeout=30) as response:
            rows = kraken_rows(response.read())
    print(json.dumps(compare(rows, args.size), indent=2))


if __name__ == "__main__":
    main()
