# Copyright (c) 2026 fxtradingguide.com
# SPDX-License-Identifier: MIT

"""Load the unmodified ECB SDMX-CSV sample."""

from __future__ import annotations

import csv
from dataclasses import dataclass
from pathlib import Path

SERIES_KEY = "EXR.D.USD.EUR.SP00.A"
SERIES_TITLE = "US dollar/Euro ECB reference exchange rate"
# Quoted field in TITLE_COMPL. Used to prove the CSV parser honours quotes.
SERIES_DETAIL_PREFIX = "ECB reference exchange rate, US dollar/Euro"
EXPECTED_SHA256 = "daf52fd25bac5f1e7568b2e61f787caec95dd506fbe315331cbff17be4531c2c"
EXPECTED_ROWS = 1283
EXPECTED_FIRST = ("2020-01-02", "1.1193")
EXPECTED_LAST = ("2024-12-31", "1.0389")

# strategies/shared/python/fxstudy/data.py -> strategies/
STRATEGIES_ROOT = Path(__file__).resolve().parents[3]
DATA_PATH = STRATEGIES_ROOT / "data" / "EXR.D.USD.EUR.SP00.A.csv"


@dataclass(frozen=True)
class Observation:
    date: str
    rate: float
    rate_text: str


def load_observations(path: Path | None = None) -> list[Observation]:
    """Read TIME_PERIOD and OBS_VALUE. Other columns are checked, not rewritten."""
    source = path or DATA_PATH
    with source.open(newline="", encoding="utf-8") as handle:
        reader = csv.DictReader(handle)
        rows = list(reader)
    if not rows:
        raise SystemExit(f"{source} has no observations")
    required = {"TIME_PERIOD", "OBS_VALUE", "KEY", "TITLE", "TITLE_COMPL"}
    missing = required.difference(reader.fieldnames or [])
    if missing:
        raise SystemExit(f"{source.name} is missing columns: {sorted(missing)}")
    observations: list[Observation] = []
    for row in rows:
        if row["KEY"] != SERIES_KEY:
            raise SystemExit(f"unexpected series key {row['KEY']!r}")
        if row["TITLE"] != SERIES_TITLE:
            raise SystemExit(f"unexpected series title {row['TITLE']!r}")
        detail = row["TITLE_COMPL"] or ""
        if not detail.startswith(SERIES_DETAIL_PREFIX):
            raise SystemExit("TITLE_COMPL was not parsed as a quoted field")
        text = row["OBS_VALUE"]
        if not text:
            raise SystemExit(f"blank rate on {row['TIME_PERIOD']}")
        observations.append(Observation(row["TIME_PERIOD"], float(text), text))
    observations.sort(key=lambda item: item.date)
    return observations


def assert_sample(observations: list[Observation]) -> None:
    if len(observations) != EXPECTED_ROWS:
        raise SystemExit(f"expected {EXPECTED_ROWS} rows, found {len(observations)}")
    first = observations[0]
    last = observations[-1]
    if (first.date, first.rate_text) != EXPECTED_FIRST:
        raise SystemExit(f"unexpected first row {first}")
    if (last.date, last.rate_text) != EXPECTED_LAST:
        raise SystemExit(f"unexpected last row {last}")
