"""Verify frozen EURUSD prices and derive observed weekday daily BID inputs.

MIT license, Edge Quant. Requires the frozen study protocol before audit
counts. Computes input-pattern frequencies, not trades or financial outcomes.
"""
from __future__ import annotations

import argparse
from datetime import UTC, datetime
import hashlib
import json
from pathlib import Path

import numpy as np
import pandas as pd

HERE = Path(__file__).resolve().parent
EXPECTED = "aae2133855f39143baecace64afc3e942bc4f9cb2c6026674b7d0e5c37c3a7e3"
CONTEXT_START = pd.Timestamp("2015-01-01", tz="UTC")
TEST_START = pd.Timestamp("2016-01-01", tz="UTC")
END = pd.Timestamp("2026-01-01", tz="UTC")


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def verify(directory, require_raw):
    protocol_path = HERE / "protocol.json"
    if not protocol_path.is_file():
        raise RuntimeError("Frozen protocol.json is required before audit counts")
    protocol_sha = sha(protocol_path)
    path = directory / "EURUSD_5m.csv.gz"
    manifest_path = directory / "EURUSD_5m.manifest.json"
    manifest = json.loads(manifest_path.read_text())
    actual_sha = sha(path)
    assert actual_sha == EXPECTED == manifest["file_sha256"], "Frozen processed quote hash changed"
    df = pd.read_csv(path, parse_dates=["timestamp"]).set_index("timestamp")
    assert str(df.index.tz) == "UTC"
    assert df.index.is_unique and df.index.is_monotonic_increasing
    assert (df.index.asi8 % (300 * 10**9) == 0).all()
    assert (df.index >= CONTEXT_START).all() and (df.index < END).all()
    columns = [f"{side}_{field}" for side in ["bid", "ask"] for field in ["open", "high", "low", "close"]]
    prices = df[columns].to_numpy()
    assert np.isfinite(prices).all() and (prices > 0).all()
    assert np.max(np.abs(prices * 100000 - np.rint(prices * 100000))) < 1e-7
    assert np.isfinite(df.volume).all() and (df.volume >= 0).all()
    for side in ["bid", "ask"]:
        op, hi, lo, cl = [df[f"{side}_{x}"] for x in ["open", "high", "low", "close"]]
        assert ((lo <= op) & (lo <= cl) & (hi >= op) & (hi >= cl)).all()
    assert ((df.ask_open >= df.bid_open) & (df.ask_close >= df.bid_close)).all()
    raw_checks = []
    for item in manifest["annual_inputs"]:
        name = f"EURUSD_M5_{item['year']}.json.gz"
        raw = directory / "raw" / name
        available = raw.is_file()
        matched = sha(raw) == item["raw_sha256"] if available else None
        assert matched is not False, f"Annual raw hash changed: {name}"
        if require_raw:
            assert available, f"Required annual raw input absent: {name}"
        raw_checks.append({"year": item["year"], "name": name, "available": available,
                           "sha256_matches_manifest": matched, "expected_sha256": item["raw_sha256"]})
    assert len(raw_checks) == 11
    all_days = df.resample("D").agg({"bid_open": "first", "bid_high": "max", "bid_low": "min", "bid_close": "last"}).dropna()
    groups = pd.Series(df.index, index=df.index).resample("D")
    all_days["m5_bar_count"] = groups.count()
    all_days["first_m5_start_utc"] = groups.first()
    all_days["last_m5_start_utc"] = groups.last()
    assert (all_days.m5_bar_count <= 288).all()
    days = all_days[all_days.index.dayofweek < 5].copy()
    days.index.name = "date"
    days["bid_close_points_1e5"] = np.rint(days.bid_close * 100000).astype("int64")
    observed_dates = pd.Series(days.index, index=days.index)
    for lag in [1, 2, 3]:
        days[f"prior_{lag}_observed_weekday_date"] = observed_dates.shift(lag)
        days[f"prior_{lag}_bid_close"] = days.bid_close.shift(lag)
    def strict_drop(previous, current):
        guard = 1e-12 * np.maximum(1, np.maximum(previous.abs(), current.abs()))
        return (previous - current) > guard
    days["three_down_pattern"] = (
        strict_drop(days.prior_1_bid_close, days.bid_close)
        & strict_drop(days.prior_2_bid_close, days.prior_1_bid_close)
        & strict_drop(days.prior_3_bid_close, days.prior_2_bid_close)
    )
    out = directory / "EURUSD_weekday_daily_bid.csv"
    days.to_csv(out, date_format="%Y-%m-%dT%H:%M:%SZ", lineterminator="\n")
    weekday_grid = pd.date_range("2015-01-01", "2025-12-31", freq="B", tz="UTC")
    missing = weekday_grid.difference(days.index)
    intervals = df.index.to_series().diff().dt.total_seconds()
    partial = days[days.m5_bar_count < 288]
    partial.to_csv(directory / "EURUSD_partial_observed_weekdays.csv", date_format="%Y-%m-%dT%H:%M:%SZ", lineterminator="\n")
    result = {
        "checked_utc": datetime.now(UTC).isoformat(), "protocol_sha256_before_audit_counts": protocol_sha,
        "new_quote_downloads": 0,
        "source_url": "https://evtradelabs.com/data",
        "provenance": "EV Trading Labs aggregates Dukascopy bid/ask candles. Frozen distributor cache; not a direct-bank export or independent tick reconciliation.",
        "input": {"file": "data/EURUSD_5m.csv.gz", "processed_sha256": actual_sha,
                  "matches_frozen_hash": True, "manifest_sha256": sha(manifest_path),
                  "original_retrieved_utc": manifest["retrieved_utc"], "original_manifest": manifest,
                  "annual_raw_hash_checks": raw_checks, "rows": len(df),
                  "test_rows_2016_2025": int(((df.index >= TEST_START) & (df.index < END)).sum()),
                  "rows_by_year": {str(y): int(n) for y, n in df.groupby(df.index.year).size().items()},
                  "first_utc": df.index[0].isoformat(), "last_utc": df.index[-1].isoformat()},
        "validation": {"unique_increasing_timestamps": True, "five_minute_alignment": True,
                       "positive_finite_valid_ohlc": True, "nonnegative_finite_volume": True,
                       "crossed_bid_ask_open_close_count": 0, "five_decimal_price_grid": True},
        "weekday_daily_bid": {"file": "data/EURUSD_weekday_daily_bid.csv", "sha256": sha(out),
                              "definition": "Actual BID OHLC over UTC [00:00,next00:00), observed Monday-Friday dates only; no missing date imputation",
                              "rows_2015_2025": len(days), "test_rows_2016_2025": int((days.index >= TEST_START).sum()),
                              "rows_by_year": {str(y): int(n) for y, n in days.groupby(days.index.year).size().items()},
                              "observed_sunday_signal_dates_excluded": int((all_days.index.dayofweek == 6).sum()),
                              "observed_saturday_signal_dates_excluded": int((all_days.index.dayofweek == 5).sum()),
                              "missing_calendar_weekdays": [x.strftime("%Y-%m-%d") for x in missing],
                              "observed_weekdays_under_288_m5_bars": len(partial),
                              "partial_day_file": "data/EURUSD_partial_observed_weekdays.csv",
                              "coverage_interpretation": "Observed partial UTC days include normal Friday closes/holidays and are not automatically provider outages."},
        "initial_context": {"latest_completed_2015_weekday": days.index[days.index < TEST_START][-1].strftime("%Y-%m-%d"),
                            "first_test_quote_utc": df.index[df.index >= TEST_START][0].isoformat(),
                            "rule": "2015 closes support only the latest completed 2015 weekday seed and its required prior observations. Portfolio starts flat in 2016; no 2015 positions."},
        "pattern_input_audit": {
            "calculated_after_protocol_freeze": True,
            "condition": "Four successive observed weekday closes with three strict decreases; equality breaks the sequence",
            "adjacent_pair_numerical_guard": "previous-current >1e-12*max(1,abs(previous),abs(current))",
            "test_pattern_dates": int(days.loc[days.index >= TEST_START, "three_down_pattern"].sum()),
            "latest_2015_seed_pattern": bool(days.loc[days.index < TEST_START, "three_down_pattern"].iloc[-1]),
            "scope": "Input-pattern flags and frequencies only; not trade counts, position simulation or financial results",
        },
        "observed_gap_coverage": {"maximum_start_gap_hours": float(intervals.max() / 3600),
                                  "gaps_over_96h": int((intervals > 96 * 3600).sum()),
                                  "interpretation": "Absences may reflect market hours, holidays, liquidity or provider coverage; cause is not independently verified."},
        "financial_outcomes_calculated": False,
        "limitations": ["Five-minute quotes and partial weekday days remain as observed; missing quotes/dates are never fabricated.",
                        "Hash/format validation does not prove all tradable observations were supplied.",
                        "Source SPY equity closes differ from this EURUSD UTC BID convention.",
                        "A next-observed-weekday exit must respond to completed day events, not assume a future calendar or fixed 24-hour hold.",
                        "Bid/ask OHLC extrema can occur at different times inside a candle.",
                        "Five-minute data cannot certify tick-level FTMO compliance."],
    }
    assert sha(protocol_path) == protocol_sha, "Protocol changed during audit"
    (HERE / "data_quality.json").write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps({"processed_sha256": actual_sha, "raw_hashes_verified": sum(x["sha256_matches_manifest"] is True for x in raw_checks),
                      "daily_rows_2015_2025": len(days), "daily_test_rows_2016_2025": result["weekday_daily_bid"]["test_rows_2016_2025"],
                      "pattern_input_audit": result["pattern_input_audit"], "financial_outcomes_calculated": False}, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-directory", type=Path, default=HERE / "data")
    parser.add_argument("--require-raw", action="store_true")
    args = parser.parse_args()
    verify(args.data_directory, args.require_raw)
