"""Download attributed Dukascopy bid/ask candles via EV Trading Labs.

Original implementation for Edge Quant. MIT license. Requires Python 3.11+,
pandas. No credentials, no synthetic/interpolated prices. End is exclusive.
Data source: https://evtradelabs.com/data (Dukascopy aggregation, attributed).
Legacy Dukascopy datafeed responded HTTP429 pointing to AWS Requester Pays;
this distributor is explicitly identified rather than presented as direct.
"""
from __future__ import annotations

import argparse
import csv
import gzip
import hashlib
import io
import json
import math
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from pathlib import Path

import pandas as pd

BASE = Path(__file__).resolve().parent / "data"
URL = "https://evtradelabs.com/api/simulator/data/{symbol}/{period}/{year}.json.gz"
KEYS = ("o", "h", "l", "c", "ao", "ah", "al", "ac")
HEADER = ("timestamp", "bid_open", "bid_high", "bid_low", "bid_close",
          "ask_open", "ask_high", "ask_low", "ask_close", "volume")


def get_year(spec):
    symbol, period, year, directory = spec
    url = URL.format(symbol=symbol, period=period, year=year)
    raw_path = directory / "raw" / f"{symbol}_{period}_{year}.json.gz"
    raw_path.parent.mkdir(parents=True, exist_ok=True)
    if raw_path.exists():
        compressed = raw_path.read_bytes()
    else:
        request = urllib.request.Request(url, headers={
            "User-Agent": "EdgeQuantResearch/1.0 historical candles",
            "Accept": "application/gzip",
        })
        for attempt in range(3):
            try:
                with urllib.request.urlopen(request, timeout=60) as response:
                    compressed = response.read()
                json.loads(gzip.decompress(compressed))
                raw_path.write_bytes(compressed)
                break
            except urllib.error.HTTPError as error:
                if error.code == 429:
                    # Respect provider throttling; do not move to another route.
                    raise RuntimeError(f"Provider rate limit at {url}; stopped") from error
                if error.code < 500 or attempt == 2:
                    raise
                time.sleep(2 ** attempt)
            except (OSError, ValueError):
                if attempt == 2:
                    raise
                time.sleep(2 ** attempt)
    rows = json.loads(gzip.decompress(compressed))
    if not isinstance(rows, list) or not rows:
        raise ValueError(f"Empty/unrecognized response at {url}")
    print(f"Fetched {symbol} {period} {year}: {len(rows):,} candles", flush=True)
    return rows, {"year": year, "url": url, "raw_candles": len(rows),
                  "raw_sha256": hashlib.sha256(compressed).hexdigest(),
                  "raw_bytes": len(compressed)}


def download(symbol, period, start_year, end_year, directory, workers):
    directory.mkdir(parents=True, exist_ok=True)
    interval = {"M5": 300, "H1": 3600}[period]
    suffix = "5m" if period == "M5" else "1h"
    output = directory / f"{symbol}_{suffix}.csv.gz"
    specs = [(symbol, period, y, directory) for y in range(start_year, end_year + 1)]
    valid, invalid, crossed, inputs = [], [], [], []
    last = -1
    with ThreadPoolExecutor(max_workers=workers) as pool:
        for rows, provenance in pool.map(get_year, specs):
            inputs.append(provenance)
            for row in rows:
                stamp = row["ts"]
                if stamp % interval or stamp <= last:
                    raise ValueError(f"Bad time alignment/order at {symbol} {stamp}")
                last = stamp
                prices = tuple(row[k] for k in KEYS)
                volume = row["v"]
                iso = datetime.fromtimestamp(stamp, UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
                if not all(x is not None and math.isfinite(x) and x > 0 for x in prices):
                    invalid.append(iso)
                    continue
                if any(not prices[o + 2] <= min(prices[o], prices[o + 3]) <= max(prices[o], prices[o + 3]) <= prices[o + 1] for o in (0, 4)):
                    invalid.append(iso)
                    continue
                if not math.isfinite(volume) or volume < 0:
                    invalid.append(iso)
                    continue
                if prices[4] < prices[0] or prices[7] < prices[3]:
                    crossed.append(iso)
                    raise ValueError(f"Crossed open/close at {symbol} {iso}")
                valid.append((iso, *prices, volume))
    if invalid:
        raise ValueError(f"Invalid candles require inspection: {symbol}: {invalid[:10]}")
    with output.open("wb") as stream:
        with gzip.GzipFile(filename="", mode="wb", fileobj=stream, mtime=0, compresslevel=5) as packed:
            with io.TextIOWrapper(packed, encoding="utf-8", newline="") as text:
                writer = csv.writer(text)
                writer.writerow(HEADER)
                writer.writerows(valid)
    df = pd.DataFrame(valid, columns=HEADER)
    df["timestamp"] = pd.to_datetime(df.timestamp, utc=True)
    df = df.set_index("timestamp")
    daily = df.resample("D").agg({
        "bid_open": "first", "bid_high": "max", "bid_low": "min", "bid_close": "last",
        "ask_open": "first", "ask_high": "max", "ask_low": "min", "ask_close": "last", "volume": "sum",
    }).dropna()
    daily.index.name = "date"
    daily.to_csv(directory / f"{symbol}_daily.csv", date_format="%Y-%m-%d")
    years = df.groupby(df.index.year).size()
    gaps = df.index.to_series().diff().dt.total_seconds()
    manifest = {
        "retrieved_utc": datetime.now(UTC).isoformat(),
        "source": "https://evtradelabs.com/data",
        "attribution": "EV Trading Labs, aggregated from Dukascopy ticks",
        "provenance_limit": "Distributor attribution; not independently reconciled against original Dukascopy ticks.",
        "symbol": symbol, "period": period, "interval_seconds": interval,
        "requested_start": f"{start_year}-01-01T00:00:00Z",
        "requested_end_exclusive": f"{end_year + 1}-01-01T00:00:00Z",
        "first_utc": df.index[0].isoformat(), "last_utc": df.index[-1].isoformat(),
        "candles": len(df), "daily_candles": len(daily),
        "candles_by_year": {str(k): int(v) for k, v in years.items()},
        "invalid_count": len(invalid), "crossed_count": len(crossed),
        "maximum_gap_hours_includes_weekends_holidays": float(gaps.max() / 3600),
        "gaps_longer_than_96h": [x.isoformat() for x in gaps[gaps > 96 * 3600].index],
        "file_sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
        "daily_sha256": hashlib.sha256((directory / f"{symbol}_daily.csv").read_bytes()).hexdigest(),
        "annual_inputs": inputs,
        "notes": ["Timestamps are candle opens UTC.", "No missing prices imputed.",
                  "Bid and ask extrema can occur at different times within each candle.",
                  "Daily OHLC aggregated by UTC date; sessions differ from broker server time.",
                  "CFD proxy quotes, not FTMO execution prices; funding must be modeled separately."],
    }
    (directory / f"{symbol}_{suffix}.manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    print(f"Wrote {output}: {len(df):,} candles, {len(daily):,} daily rows", flush=True)
    return manifest


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--symbols", nargs="+", default=["XAUUSD", "EURUSD"])
    parser.add_argument("--period", choices=["M5", "H1"], default="M5")
    parser.add_argument("--start-year", type=int, default=2016)
    parser.add_argument("--end-year", type=int, default=2025)
    parser.add_argument("--workers", type=int, default=3)
    parser.add_argument("--directory", type=Path, default=BASE)
    args = parser.parse_args()
    if args.start_year > args.end_year or not 1 <= args.workers <= 4:
        parser.error("Require start <= end and workers between1 and4")
    for symbol in args.symbols:
        download(symbol, args.period, args.start_year, args.end_year, args.directory, args.workers)
