"""Verify frozen quotes/calendar and audit complete NY core-session inputs.

MIT license, Edge Quant. Requires protocol.json before pattern counts. No
trade P&L is computed and no missing quote/session observations are filled.
"""
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
QUOTE_SHA = "aae2133855f39143baecace64afc3e942bc4f9cb2c6026674b7d0e5c37c3a7e3"
CALENDAR_SHA = "3cbbac4e5d20f5f2471fb476521a6106b6a6b3959e808dc380d86e3c4f10558d"
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 = HERE / "protocol.json"
    if not protocol.is_file():
        raise RuntimeError("Freeze protocol.json before computing audit counts")
    protocol_sha = sha(protocol)
    qp, mp = directory / "EURUSD_5m.csv.gz", directory / "EURUSD_5m.manifest.json"
    manifest = json.loads(mp.read_text())
    assert sha(qp) == QUOTE_SHA == manifest["file_sha256"], "Frozen quote hash mismatch"
    cal_path, cm_path = HERE / "sessions.csv", HERE / "sessions.manifest.json"
    cm = json.loads(cm_path.read_text())
    assert sha(cal_path) == CALENDAR_SHA == cm["session_csv_sha256"], "Frozen calendar hash mismatch"
    cal = pd.read_csv(cal_path, parse_dates=["open_utc", "close_utc"])
    assert cal.date.is_unique and cal.date.is_monotonic_increasing
    assert (cal.close_unix > cal.open_unix).all()
    assert ((cal.open_utc.astype("int64") // 10**9) == cal.open_unix).all()
    assert ((cal.close_utc.astype("int64") // 10**9) == cal.close_unix).all()
    assert (cal.open_utc.dt.tz_convert("America/New_York").dt.hour == 9).all()
    assert (cal.open_utc.dt.tz_convert("America/New_York").dt.minute == 30).all()
    assert not cal.date.isin(["2018-12-05", "2025-01-09"]).any()
    df = pd.read_csv(qp, parse_dates=["timestamp"]).set_index("timestamp")
    assert str(df.index.tz) == "UTC" and df.index.is_unique and df.index.is_monotonic_increasing
    assert (df.index.asi8 % (300 * 10**9) == 0).all()
    columns = [f"{side}_{x}" for side in ["bid", "ask"] for x in ["open", "high", "low", "close"]]
    values = df[columns].to_numpy()
    assert np.isfinite(values).all() and (values > 0).all()
    assert np.max(np.abs(values * 100000 - np.rint(values * 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"
        rp = directory / "raw" / name
        available = rp.is_file()
        matched = sha(rp) == item["raw_sha256"] if available else None
        assert matched is not False, f"Raw annual hash mismatch: {name}"
        if require_raw:
            assert available, f"Missing required annual input: {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
    records = []
    for i, session in cal.iterrows():
        if not "2015-01-01" <= session.date <= "2025-12-31":
            continue
        op, cl = session.open_utc, session.close_utc
        expected = pd.date_range(op, cl, freq="5min", inclusive="left")
        assert len(expected) in {78, 42}
        locations = df.index.get_indexer(expected)
        missing = expected[locations < 0]
        complete = len(missing) == 0
        first_low_time, low_points, tied_minimum_bars, signal = None, None, None, False
        if complete:
            low_grid = np.rint(df.iloc[locations].bid_low.to_numpy() * 100000).astype("int64")
            first_minimum = int(low_grid.argmin())
            low_points = int(low_grid[first_minimum])
            tied_minimum_bars = int((low_grid == low_points).sum())
            first_low_time = expected[first_minimum]
            signal = first_low_time >= cl - pd.Timedelta(hours=1)
        nxt = cal.iloc[i + 1]
        next_open = nxt.open_utc
        entry_in_test = START <= next_open < END
        opening_quote_exists = next_open in df.index
        deadline = next_open + pd.Timedelta(hours=2)
        exit_i = df.index.get_indexer([deadline], method="backfill")[0]
        exit_stamp = df.index[exit_i] if exit_i >= 0 else None
        records.append({
            "prior_session_date": session.date, "prior_open_utc": op.isoformat(), "prior_close_utc": cl.isoformat(),
            "is_early_close": int(session.is_early_close), "expected_m5_rows": len(expected),
            "observed_expected_rows": int((locations >= 0).sum()), "complete_core_session": complete,
            "missing_m5_rows": len(missing), "missing_m5_starts_utc": ";".join(x.isoformat() for x in missing),
            "minimum_bid_low_points_1e5": low_points, "equal_minimum_bar_count": tied_minimum_bars,
            "earliest_minimum_bar_start_utc": first_low_time.isoformat() if first_low_time is not None else "",
            "last_hour_start_utc": (cl - pd.Timedelta(hours=1)).isoformat(),
            "complete_session_last_hour_low_pattern": bool(signal),
            "next_session_date": nxt.date, "next_open_utc": next_open.isoformat(),
            "next_open_inside_test_window": entry_in_test, "exact_next_open_quote_exists": opening_quote_exists,
            "input_candidate_with_exact_test_open": bool(signal and entry_in_test and opening_quote_exists),
            "scheduled_exit_utc": deadline.isoformat(),
            "first_quote_at_or_after_exit_deadline_utc": exit_stamp.isoformat() if exit_stamp is not None else "",
            "exit_quote_delay_seconds": (exit_stamp - deadline).total_seconds() if exit_stamp is not None else None,
            "entry_fx_age_seconds": 0 if opening_quote_exists else None,
        })
    audit = pd.DataFrame(records)
    output = directory / "EURUSD_core_session_low_audit.csv"
    audit.to_csv(output, index=False, lineterminator="\n")
    tests = audit[audit.next_open_inside_test_window]
    candidates = tests[tests.complete_session_last_hour_low_pattern]
    eligible = tests[tests.input_candidate_with_exact_test_open]
    intervals = df.index.to_series().diff().dt.total_seconds()
    result = {
        "checked_utc": datetime.now(UTC).isoformat(), "protocol_sha256_before_counts": protocol_sha,
        "new_quote_downloads": 0,
        "quote_provenance": "EV Trading Labs aggregates Dukascopy bid/ask candles. Explicit distributor attribution; not direct-bank export or independent tick reconciliation.",
        "source_url": "https://evtradelabs.com/data",
        "quote_input": {"file": "data/EURUSD_5m.csv.gz", "processed_sha256": QUOTE_SHA,
                        "original_manifest": manifest, "manifest_sha256": sha(mp),
                        "original_retrieved_utc": manifest["retrieved_utc"], "annual_raw_hash_checks": raw_checks,
                        "rows": len(df), "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(),
                        "maximum_observed_start_gap_hours": float(intervals.max() / 3600),
                        "gaps_over_96h": int((intervals > 96 * 3600).sum()),
                        "format_and_ohlc_checks_passed": True},
        "calendar": {"file": "sessions.csv", "sha256": CALENDAR_SHA, "manifest": cm,
                     "origin": "Copied unchanged from the existing frozen XNYS calendar generated with exchange_calendars 4.13.3",
                     "scope": "2015–2030 known NYSE core-session rules; future unscheduled closures require regeneration",
                     "calendar_is_exogenous_not_future_price_selection": True,
                     "closed_bush_2018_12_05_and_carter_2025_01_09_assertions_passed": True},
        "core_session_audit": {"file": "data/EURUSD_core_session_low_audit.csv", "sha256": sha(output),
                               "prior_sessions_2015_2025": len(audit), "test_next_session_open_count": len(tests),
                               "expected_rows_normal": 78, "expected_rows_early_close": 42,
                               "complete_test_prior_sessions": int(tests.complete_core_session.sum()),
                               "incomplete_test_prior_sessions": int((~tests.complete_core_session).sum()),
                               "complete_prior_last_hour_low_candidates": len(candidates),
                               "candidates_missing_exact_next_open_quote": int((~candidates.exact_next_open_quote_exists).sum()),
                               "input_candidates_with_exact_test_open": len(eligible),
                               "eligible_exit_delay_gt_zero_count": int((eligible.exit_quote_delay_seconds > 0).sum()),
                               "eligible_maximum_exit_delay_seconds": float(eligible.exit_quote_delay_seconds.max()) if len(eligible) else None,
                               "first_2016_entry_session_context": tests.iloc[0].to_dict()},
        "min_tie_policy": "Minimum BID low on literal five-decimal quote grid; FIRST earliest bar start among exact ties. No epsilon merging of different points.",
        "entry_fx_note": "The EURUSD strategy and conversion use the same observed quote source; an exact opening quote has zero conversion age.",
        "financial_outcomes_calculated": False,
        "limitations": ["A missing core bar causes a source session to fail completeness; no partial-session fallback or quote interpolation.",
                        "The calendar, New York core-window definition, tie policy and FX transfer are adaptation choices, not literal statements from the source post.",
                        "Five-minute bar minima locate an interval, not the exact tick time of the minimum.",
                        "Source SPY prices and these EURUSD BID quotes are different markets.",
                        "Calendar/quote hashes and OHLC checks cannot prove all tradable ticks were supplied.",
                        "Five-minute data do not certify tick-level FTMO compliance."],
    }
    assert sha(protocol) == protocol_sha, "Frozen protocol changed during audit"
    (HERE / "data_quality.json").write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps(result["core_session_audit"], 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)
