#!/usr/bin/env python3
"""Replay fixed post-signal delays on the pinned EUR/USD quote and signal files."""

from argparse import ArgumentParser
from array import array
from bisect import bisect_left
from collections import Counter
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal, ROUND_HALF_UP
from hashlib import file_digest, sha256
from pathlib import Path
from statistics import median
from typing import NamedTuple
from zipfile import ZipFile
import json

PROTOCOL_UTF8 = '''{
  "market": "EUR/USD",
  "source": "HistData EUR/USD July 2024 Generic ASCII Tick",
  "source_timezone": "Fixed EST UTC-05:00 throughout the year",
  "point_price": "0.00001",
  "points_per_pip": 10,
  "signals": "Use all 196 Ask activation rows in the pinned V266 Buy Stop and Buy Stop Limit evidence.",
  "utc_signal_dates": ["2024-07-02", "2024-07-31"],
  "quote_order": "Sort by UTC timestamp and then original one-based CSV row number. Keep ties in file order.",
  "coherence": "Use rows with positive Bid and Ask on the whole-point grid and Bid at or below Ask.",
  "delays_ms": [0, 250, 1000],
  "absolute_window_ms": 3000,
  "match": "Start at the signal row. Select the first source-ordered coherent quote at or after signal time plus delay and strictly before signal time plus 3000 ms. The zero-delay arm includes the signal row. If the window has no matching quote, record a skip.",
  "comparison": "For each matched arm subtract the same signal's zero-delay Ask and Bid in whole points. Measure request-to-quote and signal-to-quote milliseconds separately. Exclude skipped arms from change and wait summaries.",
  "paired_arms": "Report how many signals match at both 250 ms and 1000 ms and how many of those select the same source row.",
  "case_priority": [
    "Earliest signal with 1000 ms Ask above the zero-delay Ask.",
    "Earliest signal with 1000 ms Ask below the zero-delay Ask.",
    "Earliest signal with a 1000 ms skip and a 250 ms match."
  ],
  "chart_context": "For each case, use 15 archived paired Ask and Bid M1 OHLC slots centered on the signal minute, exact in-window rows, and the neighboring rows before the signal and at or after the exclusive deadline.",
  "scope": "Historical quote timing and signed price differences under fixed study delays. No orders, fills, execution slippage, fees or profit and loss are modeled."
}
'''
PROTOCOL = json.loads(PROTOCOL_UTF8)
PROTOCOL_SHA = "9f7242b764c90dc090ac6bd21595a0cc7a414ae6af33ec99f036c1c2ee84659a"
ARCHIVE = {
    "provider": "HistData.com",
    "symbol": "EURUSD",
    "format": "Generic ASCII Tick, DateTime,Bid,Ask,Volume",
    "archive_file": "HISTDATA_COM_ASCII_EURUSD_T_202407.zip",
    "archive_bytes": 8641917,
    "archive_sha256": "d46ff671cd5fd65c605d7c03496217dcbca3ed39086dc3afe202f193f518442c",
    "member": "DAT_ASCII_EURUSD_T_202407.csv",
    "member_bytes": 57086289,
    "member_crc32": "7cd97dc3",
    "member_sha256": "2caa350929f00ea49e8311d70776e56e1bfe101d72ec092cd0ffe927d5d7aa06",
    "member_records": 1463751,
    "source_url": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/7",
    "specification_url": "https://www.histdata.com/f-a-q/data-files-detailed-specification/",
    "source_utc_offset_hours": -5,
}
SIGNAL_SOURCE = {
    "site_version": 266,
    "file": "eurusd-buy-stop-limit-guide-evidence.json",
    "url": "https://myprofitfactor.com/assets/eurusd-buy-stop-limit-guide-evidence.json",
    "sha256": "55a9549afe579c34effc84f078fe45d7c6b214e9f7851564699cfb755c500be4",
    "signal_rows": 196,
    "selection": "All non-null hours[].trigger rows in the V266 evidence.",
}
DELAY_MS = PROTOCOL["delays_ms"]
WINDOW_MS = PROTOCOL["absolute_window_ms"]
HOUR_MS = 3600000
MINUTE_MS = 60000
DAY_MS = 24 * HOUR_MS
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
SHIFT_MS = -ARCHIVE["source_utc_offset_hours"] * HOUR_MS
CASE_SELECTORS = (
    "earliest_1000ms_ask_above_baseline",
    "earliest_1000ms_ask_below_baseline",
    "earliest_1000ms_skip_250ms_match",
)


def date_ms(day):
    return (day - EPOCH.date()).days * DAY_MS


def utc_text(ms):
    return (EPOCH + timedelta(milliseconds=ms)).isoformat(timespec="milliseconds").replace("+00:00", "Z")


def price_text(points):
    whole, fraction = divmod(points, 100000)
    return f"{whole}.{fraction:05d}"


class Tape(NamedTuple):
    time: array
    bid: array
    ask: array

    def record(self, i):
        return {
            "time_ms": self.time[i], "time_utc": utc_text(self.time[i]), "source_row": i + 1,
            "bid": price_text(self.bid[i]), "ask": price_text(self.ask[i]),
            "bid_points": self.bid[i], "ask_points": self.ask[i],
        }


def read_tape(path):
    if path.stat().st_size != ARCHIVE["archive_bytes"]:
        raise ValueError("ZIP size differs from the pinned HistData archive.")
    with path.open("rb") as source:
        if file_digest(source, "sha256").hexdigest() != ARCHIVE["archive_sha256"]:
            raise ValueError("ZIP SHA-256 differs from the pinned HistData archive.")
    tape = Tape(array("q"), array("i"), array("i"))
    digest = sha256()
    prior_time, source_day = None, None
    ties = zero_spreads = 0
    with ZipFile(path) as archive:
        member = archive.getinfo(ARCHIVE["member"])
        if (member.file_size, f"{member.CRC:08x}") != (ARCHIVE["member_bytes"], ARCHIVE["member_crc32"]):
            raise ValueError("CSV metadata differs from the pinned archive member.")
        with archive.open(member) as records:
            for i, line in enumerate(records, 1):
                digest.update(line)
                stamp, bid_field, ask_field, _volume = line.split(b",")
                if stamp[:8] != source_day:
                    source_day = stamp[:8]
                    day = date(int(source_day[:4]), int(source_day[4:6]), int(source_day[6:8]))
                    local_midnight = date_ms(day) + SHIFT_MS
                hh, mm, ss, ms = int(stamp[9:11]), int(stamp[11:13]), int(stamp[13:15]), int(stamp[15:18])
                assert len(stamp) == 18 and stamp[8:9] == b" "
                assert 0 <= hh < 24 and 0 <= mm < 60 and 0 <= ss < 60 and 0 <= ms < 1000
                time = local_midnight + hh * HOUR_MS + mm * MINUTE_MS + ss * 1000 + ms
                if prior_time is not None and time < prior_time:
                    raise ValueError(f"Timestamp order violation at CSV row {i}.")
                ties += time == prior_time
                prior_time = time
                bid, bid_tail = divmod(int(bid_field.replace(b".", b"")), 10)
                ask, ask_tail = divmod(int(ask_field.replace(b".", b"")), 10)
                if bid_field[-7:-6] != b"." or ask_field[-7:-6] != b"." or bid_tail or ask_tail or not 0 < bid <= ask:
                    raise ValueError(f"Incoherent quote at pinned CSV row {i}.")
                zero_spreads += bid == ask
                tape.time.append(time)
                tape.bid.append(bid)
                tape.ask.append(ask)
    if digest.hexdigest() != ARCHIVE["member_sha256"] or len(tape.time) != ARCHIVE["member_records"]:
        raise ValueError("CSV SHA-256 or row count differs from the pinned archive member.")
    return tape, {
        "zip_sha256_matched": True, "csv_sha256_matched": True, "csv_crc32_matched": True,
        "coherent_quote_rows": len(tape.time), "nondecreasing_timestamps": True,
        "rows_sharing_preceding_timestamp": ties, "zero_spread_rows": zero_spreads,
        "first_time_utc": utc_text(tape.time[0]), "last_time_utc": utc_text(tape.time[-1]),
    }


def read_signals(path, tape):
    source = path.read_bytes()
    if sha256(source).hexdigest() != SIGNAL_SOURCE["sha256"]:
        raise ValueError("Signal JSON SHA-256 differs from the pinned V266 evidence.")
    proof = json.loads(source)
    assert proof["archive"]["archive_sha256"] == ARCHIVE["archive_sha256"]
    assert proof["archive"]["member_sha256"] == ARCHIVE["member_sha256"]
    first, last = (date_ms(date.fromisoformat(day)) for day in PROTOCOL["utc_signal_dates"])
    signals = []
    for hour in proof["hours"]:
        if hour["trigger"] is None:
            continue
        signal = hour["trigger"]
        i = signal["source_row"] - 1
        assert 0 <= i < len(tape.time)
        if signal != tape.record(i):
            raise ValueError(f"Signal row {i + 1} does not match its original quote.")
        assert first <= signal["time_ms"] < last + DAY_MS
        assert hour["hour_start_ms"] <= signal["time_ms"] < hour["expiry_ms"]
        assert not signals or signals[-1][0] < i
        signals.append((i, hour["hour_start_ms"]))
    assert len(signals) == SIGNAL_SOURCE["signal_rows"] == proof["summary"]["activated_hours"]
    return signals


def match_observation(tape, signal_index, hour_start):
    t = tape.time[signal_index]
    deadline = t + WINDOW_MS
    end = bisect_left(tape.time, deadline, lo=signal_index)
    by_delay, selected = {}, {}
    for delay in DELAY_MS:
        request = t + delay
        i = bisect_left(tape.time, request, lo=signal_index, hi=end)
        hit = i < end
        if hit:
            selected[delay] = i
        by_delay[str(delay)] = {
            "delay_ms": delay, "request_ms": request, "request_utc": utc_text(request),
            "status": "hit" if hit else "skip", "quote": tape.record(i) if hit else None,
            "wait_after_request_ms": tape.time[i] - request if hit else None,
            "elapsed_since_signal_ms": tape.time[i] - t if hit else None,
            "ask_delta_points": tape.ask[i] - tape.ask[signal_index] if hit else None,
            "bid_delta_points": tape.bid[i] - tape.bid[signal_index] if hit else None,
        }
    assert selected[0] == signal_index
    return {
        "signal": tape.record(signal_index), "source_hour_start_ms": hour_start,
        "source_hour_start_utc": utc_text(hour_start), "deadline_ms": deadline,
        "deadline_utc": utc_text(deadline), "delays": by_delay,
    }, selected, end


def candle(values):
    if not values:
        return None
    return dict(zip(("open", "high", "low", "close"),
                    map(price_text, (values[0], max(values), min(values), values[-1])), strict=True))


def chart_case(selection, tape, observation, i, selected, end):
    signal_time = tape.time[i]
    signal_minute = signal_time // MINUTE_MS * MINUTE_MS
    minutes = []
    for offset in range(-7, 8):
        minute = signal_minute + offset * MINUTE_MS
        start = bisect_left(tape.time, minute)
        stop = bisect_left(tape.time, minute + MINUTE_MS, lo=start)
        minutes.append({
            "time_ms": minute, "time_utc": utc_text(minute), "minute_offset": offset,
            "quote_rows": stop - start, "bid": candle(tape.bid[start:stop]), "ask": candle(tape.ask[start:stop]),
        })

    def window_record(j):
        return tape.record(j) | {
            "offset_ms": tape.time[j] - signal_time, "offset_rows": j - i,
            "selected_delays_ms": [delay for delay, k in selected.items() if k == j],
        }

    return {
        "selection": selection, "observation": observation, "m1": minutes,
        "window_quotes": [window_record(j) for j in range(i, end)],
        "previous_quote": window_record(i - 1) if i > 0 else None,
        "first_at_or_after_deadline": window_record(end) if end < len(tape.time) else None,
    }


def stats(values):
    return {
        "min": min(values, default=None), "median": median(values) if values else None,
        "max": max(values, default=None), "distribution": dict(sorted(Counter(values).items())),
    }


def delta_stats(values):
    return stats(values) | {
        "negative_count": sum(x < 0 for x in values), "zero_count": values.count(0),
        "positive_count": sum(x > 0 for x in values),
    }


def summarize(observations):
    total = len(observations)
    by_delay = {}
    for delay in map(str, DELAY_MS):
        hits = [row["delays"][delay] for row in observations if row["delays"][delay]["status"] == "hit"]
        percent = (Decimal(100) * len(hits) / total).quantize(Decimal("0.000001"), rounding=ROUND_HALF_UP)
        by_delay[delay] = {
            "delay_ms": int(delay), "hits": len(hits), "skips": total - len(hits),
            "hit_rate": {"numerator": len(hits), "denominator": total, "percent": str(percent)},
            "ask_delta_points": delta_stats([x["ask_delta_points"] for x in hits]),
            "bid_delta_points": delta_stats([x["bid_delta_points"] for x in hits]),
            "wait_after_request_ms": stats([x["wait_after_request_ms"] for x in hits]),
            "elapsed_since_signal_ms": stats([x["elapsed_since_signal_ms"] for x in hits]),
        }
    overlaps = Counter()
    for row in observations:
        fast, slow = (row["delays"][delay]["quote"] for delay in ("250", "1000"))
        if fast and slow:
            overlaps["both_hit"] += 1
            overlaps["same_source_row" if fast["source_row"] == slow["source_row"] else "different_source_rows"] += 1
        elif fast:
            overlaps["only_250_hit"] += 1
        elif slow:
            overlaps["only_1000_hit"] += 1
        else:
            overlaps["neither_hit"] += 1
    assert overlaps["both_hit"] == overlaps["same_source_row"] + overlaps["different_source_rows"]
    assert total == sum(overlaps[key] for key in ("both_hit", "only_250_hit", "only_1000_hit", "neither_hit"))
    return {
        "signals": total, "delays": by_delay,
        "overlap_250_1000": {key: overlaps[key] for key in ("both_hit", "same_source_row", "different_source_rows",
                                                         "only_250_hit", "only_1000_hit", "neither_hit")},
    }


def compute(archive_path, signals_path):
    tape, validation = read_tape(archive_path)
    signals = read_signals(signals_path, tape)
    observations, cases = [], {}
    for signal_index, hour_start in signals:
        row, selected, end = match_observation(tape, signal_index, hour_start)
        observations.append(row)
        ask_delta = row["delays"]["1000"]["ask_delta_points"]
        conditions = (ask_delta is not None and ask_delta > 0, ask_delta is not None and ask_delta < 0,
                      1000 not in selected and 250 in selected)
        for name, condition in zip(CASE_SELECTORS, conditions, strict=True):
            if condition and name not in cases:
                cases[name] = chart_case(name, tape, row, signal_index, selected, end)
    validation.update({"signal_json_sha256_matched": True, "signal_rows_matched_to_tape": len(signals)})
    return {
        "protocol": PROTOCOL, "protocol_sha256": PROTOCOL_SHA,
        "sources": {"histdata_archive": ARCHIVE, "v266_signal_evidence": SIGNAL_SOURCE},
        "validation": validation, "summary": summarize(observations), "observations": observations,
        "cases": [cases[name] for name in CASE_SELECTORS if name in cases],
    }


def main():
    here = Path(__file__).resolve().parent
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("archive", type=Path, help="Pinned July 2024 HistData Generic ASCII Tick EUR/USD ZIP.")
    parser.add_argument("signals", type=Path, help="Pinned V266 EUR/USD Buy Stop Limit evidence JSON.")
    parser.add_argument("--output", type=Path, default=here / "evidence.json")
    args = parser.parse_args()
    assert sha256(PROTOCOL_UTF8.encode("utf-8")).hexdigest() == PROTOCOL_SHA
    protocol = here / "protocol.json"
    if protocol.exists():
        assert protocol.read_bytes() == PROTOCOL_UTF8.encode("utf-8")
    evidence = compute(args.archive, args.signals)
    args.output.write_text(json.dumps(evidence, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
    print(json.dumps({
        "signals": evidence["summary"]["signals"],
        "delay_matches": {key: {"hits": row["hits"], "skips": row["skips"]}
                          for key, row in evidence["summary"]["delays"].items()},
        "overlap_250_1000": evidence["summary"]["overlap_250_1000"],
    }, indent=2))


if __name__ == "__main__":
    main()
