"""Verify frozen EURUSD/calendar inputs and audit the fixed monthly schedule.

MIT license, Edge Quant. Requires protocol.json before counts. Produces no
trade profits; exit quote availability never filters an entry candidate.
"""
from __future__ import annotations

import argparse
from datetime import UTC, date, datetime, timedelta
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"


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


def third_friday(year, month):
    first = date(year, month, 1)
    result = first + timedelta(days=(4 - first.weekday()) % 7 + 14)
    assert result.weekday() == 4 and 15 <= result.day <= 21
    return result


def verify(directory, require_raw):
    protocol_path = HERE / "protocol.json"
    if not protocol_path.is_file():
        raise RuntimeError("Freeze protocol.json before schedule audit counts")
    protocol_sha = sha(protocol_path)
    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"
    cm = json.loads((HERE / "sessions.manifest.json").read_text())
    assert sha(HERE / "sessions.csv") == CALENDAR_SHA == cm["session_csv_sha256"], "Frozen calendar hash mismatch"
    cal = pd.read_csv(HERE / "sessions.csv", parse_dates=["open_utc", "close_utc"])
    assert cal.date.is_unique and cal.date.is_monotonic_increasing
    assert ((cal.open_utc.astype("int64") // 10**9) == cal.open_unix).all()
    assert ((cal.close_utc.astype("int64") // 10**9) == cal.close_unix).all()
    local_open = cal.open_utc.dt.tz_convert("America/New_York")
    assert ((local_open.dt.hour == 9) & (local_open.dt.minute == 30)).all()
    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()
    cols = [f"{side}_{field}" for side in ["bid", "ask"] for field in ["open", "high", "low", "close"]]
    values = df[cols].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}_{field}"] for field 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"Raw annual hash mismatch: {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
    assert third_friday(2024, 6) == date(2024, 6, 21), "Saturday-start-month literal Friday anchor failed"
    plans = []
    for year in range(2016, 2026):
        for month in range(1, 13):
            friday = third_friday(year, month)
            monday = friday - timedelta(days=4)
            sessions = cal[(cal.date >= monday.isoformat()) & (cal.date <= friday.isoformat())]
            assert not sessions.empty
            first, last = sessions.iloc[0], sessions.iloc[-1]
            entry, exit_target = first.open_utc, last.close_utc
            assert entry < exit_target
            exact_entry = entry in df.index
            exit_i = df.index.get_indexer([exit_target], method="backfill")[0]
            actual_exit = df.index[exit_i] if exit_i >= 0 else None
            plans.append({"year": year, "month": month, "literal_third_friday": friday.isoformat(),
                          "week_monday": monday.isoformat(), "week_friday": friday.isoformat(),
                          "entry_session_date": first.date, "entry_open_utc": entry.isoformat(),
                          "exit_session_date": last.date, "exit_close_target_utc": exit_target.isoformat(),
                          "exact_entry_quote_exists": exact_entry,
                          "entry_fx_age_seconds": 0 if exact_entry else None,
                          "exact_exit_target_quote_exists": exit_target in df.index,
                          "first_quote_at_or_after_exit_target_utc": actual_exit.isoformat() if actual_exit is not None else "",
                          "exit_quote_delay_seconds": (actual_exit - exit_target).total_seconds() if actual_exit is not None else None,
                          "entry_month_filter": "none; every month included"})
    audit = pd.DataFrame(plans)
    assert len(audit) == 120 and (audit.groupby("year").size() == 12).all()
    output = directory / "opex_schedule_audit.csv"
    audit.to_csv(output, index=False, lineterminator="\n")
    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 supplies aggregated Dukascopy bid/ask candles. Distributor attribution; not direct-bank export or independent tick reconciliation.",
        "quote_input": {"file": "data/EURUSD_5m.csv.gz", "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_start_gap_hours": float(intervals.max() / 3600), "gaps_over_96h": int((intervals > 96 * 3600).sum()),
                        "hash_and_ohlc_validation_passed": True},
        "calendar": {"file": "sessions.csv", "sha256": CALENDAR_SHA, "manifest": cm,
                     "copied_unchanged": True, "basis": "Literal third Friday, day 15–21, and first/last XNYS session in Monday–Friday week",
                     "third_saturday_parenthetical_not_used": True,
                     "saturday_start_month_anchor": "June 2024 third Friday is 21 June, not 14 June",
                     "actual_fx_option_expiration_claimed": False},
        "schedule_audit": {"file": "data/opex_schedule_audit.csv", "sha256": sha(output),
                           "all_months_included": True, "predefined_monthly_windows": len(audit),
                           "missing_exact_entry_quotes": int((~audit.exact_entry_quote_exists).sum()),
                           "exit_target_quote_absent": int((~audit.exact_exit_target_quote_exists).sum()),
                           "delayed_exit_quotes": int((audit.exit_quote_delay_seconds > 0).sum()),
                           "exit_availability_never_filters_entry": True},
        "ftmo_note": {"file": "FTMO_RULES.md", "sha256": sha(HERE / "FTMO_RULES.md"),
                      "copied_unchanged_from": "/workspace/research-last-hour-low/FTMO_RULES.md",
                      "contains_root_30_november_recheck": True},
        "financial_outcomes_calculated": False,
        "limitations": ["US equity monthly-expiration calendar is transferred to EURUSD; this is not an FX-options strategy or claimed FX expiration effect.",
                        "Source equity opening/closing conventions differ from first observed FX quote executions at the scheduled timestamps.",
                        "Quote/calendar hashes and OHLC validation cannot prove complete tradable tick coverage.",
                        "Missing exact opening quote skips entry; an exit gap retains the pending exit rather than selecting trades by future exit availability.",
                        "No quote/session prices are imputed.", "Five-minute observations 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(result["schedule_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)
