"""Reproduce the November 2024 Renko study.

Keep renko_lab.py and renko_resolution.py beside this script.
Output: JSON with daily statistics and 30 independent trade samples per asset.
"""
import csv
import json
import time
from datetime import datetime, timedelta, timezone
from decimal import Decimal, ROUND_HALF_UP
from statistics import median
from urllib.request import urlopen

from renko_lab import describe
from renko_resolution import compare

START = datetime(2024, 11, 1, tzinfo=timezone.utc)
DAYS = 30
END = START + timedelta(days=DAYS)
ASSETS = ("BTC", "ETH")
SIZES = (1, 2)


def text(url):
    with urlopen(url, timeout=30) as reply:
        return reply.read().decode("utf-8-sig")


def fixed(first, bps, precision):
    return (Decimal(first) * bps / 10_000).quantize(Decimal(precision), rounding=ROUND_HALF_UP)


def collect_daily():
    series = []
    for asset in ASSETS:
        endpoint = f"https://api.exchange.coinbase.com/products/{asset}-USD/candles"
        raw = json.loads(text(f"{endpoint}?granularity=86400&start=2024-11-01T00:00:00Z&end=2024-12-01T00:00:00Z"), parse_float=Decimal)
        rows = sorted((datetime.fromtimestamp(row[0], tz=timezone.utc).date().isoformat(),
                       str(row[4])) for row in raw if START.timestamp() <= row[0] < END.timestamp())
        series.append([asset + "/USD", rows])
    rows = csv.reader(text("https://fred.stlouisfed.org/graph/fredgraph.csv?id=DEXUSEU&cosd=2024-11-01&coed=2024-11-30").splitlines())
    next(rows)
    series.append(["EUR/USD", [(day, value) for day, value in rows
                              if "2024-11-01" <= day <= "2024-11-30" and value not in ("", ".")]])
    return series


def collect_trades():
    for days in range(DAYS):
        day = START + timedelta(days=days)
        lower = int(day.timestamp()) * 1_000_000_000 - 1
        for symbol in ("XBTUSD", "ETHUSD"):
            url = f"https://api.kraken.com/0/public/Trades?pair={symbol}&count=100&since={lower}"
            response = json.loads(text(url), parse_float=Decimal)
            if response["error"]:
                raise ValueError(response["error"])
            rows = next(v for k, v in response["result"].items() if k != "last")
            yield {"pair": symbol, "day": day.date().isoformat(),
                   "rows": [(str(row[2]), row[6], row[0]) for row in rows]}
            time.sleep(1)


def summarize(daily, trades):
    daily_results = []
    expected_days = [(START + timedelta(days=i)).date().isoformat() for i in range(DAYS)]
    for asset, rows in daily:
        dates = [row[0] for row in rows]
        if dates != sorted(set(dates)) or not dates or not set(dates) <= set(expected_days):
            raise ValueError(f"{asset} daily data is incomplete or unordered")
        if asset != "EUR/USD" and dates != expected_days:
            raise ValueError(f"{asset} must have all 30 closes")
        for bps in (50, 100):
            size = fixed(rows[0][1], bps, "0.0001" if asset == "EUR/USD" else "0.01")
            daily_results.append({"asset": asset, "size": str(size), "bps": bps,
                                  **describe((row[1] for row in rows), size)})
    summaries = []
    for pair, asset in (("XBTUSD", "BTC/USD"), ("ETHUSD", "ETH/USD")):
        selected = sorted((window for window in trades if window["pair"] == pair), key=lambda window: window["day"])
        if [window["day"] for window in selected] != expected_days:
            raise ValueError(f"Missing daily windows for {pair}")
        metrics = []
        durations = []
        evaluated = 0
        for window in selected:
            raw = [(Decimal(t), int(i), Decimal(p)) for t, i, p in window["rows"]]
            if len(raw) != 100 or any(datetime.fromtimestamp(float(t), timezone.utc).date().isoformat() != window["day"]
                                      for t, _, _ in raw):
                raise ValueError(f"Invalid intraday sample: {pair} {window['day']}")
            rows = [row for row in raw if int(raw[0][0]) < row[0] < int(raw[-1][0])]
            if len(rows) < 2:
                raise ValueError(f"Empty complete-second sample for {pair}")
            sizes = [fixed(rows[0][2], bps, "0.01") for bps in SIZES]
            result = compare(rows, sizes, fast=3, slow=8)
            durations.append(float(rows[-1][0] - rows[0][0]))
            evaluated += len(rows)
            metrics.append(result["metrics"])
        for index, bps in enumerate(SIZES):
            variants = [window[index] for window in metrics]
            totals = {version: {key: sum(row[version][key] for row in variants)
                                for key in ("bricks", "reversals", "ema")} for version in ("tick", "second")}
            summaries.append({"asset": asset, "bps": bps, "windows": len(metrics), "trades": evaluated,
                              "median_seconds": round(median(durations), 1),
                              "matched_ema": sum(row["matched_ema"]["matched"] for row in variants), **totals})
    return {"daily": daily_results, "samples": summaries}


if __name__ == "__main__":
    print(json.dumps(summarize(collect_daily(), list(collect_trades())), indent=2))
