#!/usr/bin/env python3
"""Replay hypothetical EUR/USD Buy Stop and Buy Stop Limit orders on HistData quotes."""

from argparse import ArgumentParser
from collections import Counter
from datetime import date, datetime, timedelta, timezone
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 = '''{
  "source": "HistData EUR/USD Generic ASCII Tick, source-local July 2024",
  "source_timezone": "Fixed EST UTC-05:00 throughout the year",
  "point_price": "0.00001",
  "points_per_pip": 10,
  "utc_first_date_inclusive": "2024-07-02",
  "utc_last_date_inclusive": "2024-07-31",
  "schedule": "Every UTC Monday through Friday hour start on the included dates",
  "scheduled_hours": 528,
  "reference_interval_ms": 60000,
  "active_window_ms": 1800000,
  "reference": "First coherent Bid/Ask row in the opening minute. Ask at this row is A. Skip a scheduled hour if the opening minute has no coherent quote.",
  "coherence": "Both prices are positive whole points and Bid is at or below Ask. Use coherent quote rows for all sampled prices and events.",
  "buy_stop_level": "S = A + 30 points",
  "buy_limit_level": "L = S - 10 points",
  "trigger": "The first source-ordered coherent row after reference with Ask at or above S before the hour start plus 30 minutes. Both orders share this trigger. This observed Ask is the Buy Stop price proxy.",
  "limit_eligibility": "A modeled Buy Limit at L activates at the trigger. Its first subsequent coherent row with Ask at or below L and time strictly before the same expiry is quote-eligible.",
  "expiry": "Hour start plus 30 minutes, exclusive",
  "order": "Compare UTC millisecond timestamps and then original CSV row number. Keep all tied rows in file sequence.",
  "case_priority": "Earliest scheduled triggered hour with a qualifying limit quote, and earliest scheduled triggered hour reaching expiry without a qualifying limit quote.",
  "scope": "Historical Bid/Ask quote replay. Proxy prices and quote eligibility measure the archive conditions. The study omits actual fills, quote size, venue protections, slippage, fees and account rules."
}
'''
PROTOCOL = json.loads(PROTOCOL_UTF8)
PROTOCOL_SHA = "6726185f3877989ebf5a3f1779efd51b146580580d471004d7cfd7c288f02955"
ARCHIVE = {
    "provider": "HistData.com",
    "symbol": "EURUSD",
    "format": "Generic ASCII tick quotes, DateTime,Bid,Ask,Volume",
    "archive_file": "EURUSD-2024-07.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/",
    "checksum_basis": "Existing MyProfitFactor July 2024 archive manifest and prior spread study.",
    "source_utc_offset_hours": -5,
}
HOUR_MS = 3600000
MINUTE_MS = 60000
REFERENCE_MS = PROTOCOL["reference_interval_ms"]
WINDOW_MS = PROTOCOL["active_window_ms"]
STOP_OFFSET = 30
LIMIT_OFFSET = 10
QUOTE_RADIUS = 12
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
UTC_SHIFT_MS = -ARCHIVE["source_utc_offset_hours"] * HOUR_MS
CASE_ORDER = ("limit_eligible", "limit_expired")


class Quote(NamedTuple):
    time_ms: int
    source_row: int
    bid_points: int
    ask_points: int


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


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


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


def read_quotes(path, validation):
    if path.stat().st_size != ARCHIVE["archive_bytes"]:
        raise ValueError("ZIP size differs from the pinned HistData archive.")
    with path.open("rb") as compressed:
        if file_digest(compressed, "sha256").hexdigest() != ARCHIVE["archive_sha256"]:
            raise ValueError("ZIP SHA-256 differs from the pinned HistData archive.")
    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.")
        digest = sha256()
        previous_day, previous_time = None, None
        first_time = first_source = last_source = None
        stats = Counter()
        with archive.open(member) as rows:
            for index, line in enumerate(rows, 1):
                digest.update(line)
                source_stamp, bid_field, ask_field, _volume = line.split(b",")
                day = source_stamp[:8]
                if day != previous_day:
                    local_day = date(int(day[:4]), int(day[4:6]), int(day[6:8]))
                    local_midnight_in_utc = date_ms(local_day) + UTC_SHIFT_MS
                    previous_day = day
                hh, mm, ss, ms = (int(source_stamp[a:b]) for a, b in ((9, 11), (11, 13), (13, 15), (15, 18)))
                assert len(source_stamp) == 18 and source_stamp[8:9] == b" "
                assert 0 <= hh < 24 and 0 <= mm < 60 and 0 <= ss < 60 and 0 <= ms < 1000
                time = local_midnight_in_utc + hh * HOUR_MS + mm * MINUTE_MS + ss * 1000 + ms
                if previous_time is None:
                    first_time, first_source = time, source_stamp
                elif time < previous_time:
                    raise ValueError(f"CSV timestamps out of order at source row {index}.")
                elif time == previous_time:
                    stats["rows_sharing_previous_timestamp"] += 1
                previous_time, last_source = time, source_stamp
                bid, bid_fraction = divmod(int(bid_field.replace(b".", b"")), 10)
                ask, ask_fraction = divmod(int(ask_field.replace(b".", b"")), 10)
                assert bid_field[-7:-6] == ask_field[-7:-6] == b"."
                stats["archive_rows"] += 1
                if bid_fraction or ask_fraction or not (0 < bid <= ask):
                    stats["incoherent_rows"] += 1
                    continue
                stats["coherent_rows"] += 1
                if bid == ask:
                    stats["zero_spread_rows"] += 1
                yield Quote(time, index, bid, ask)
        if digest.hexdigest() != ARCHIVE["member_sha256"] or stats["archive_rows"] != ARCHIVE["member_records"]:
            raise ValueError("CSV SHA-256 or row count differs from the pinned archive member.")
    validation.update({
        "zip_sha256_matched": True, "csv_sha256_matched": True, "csv_crc32_matched": True,
        "nondecreasing_timestamps": True,
        "first_time_utc": utc_text(first_time), "last_time_utc": utc_text(previous_time),
        "first_source_timestamp_fixed_est": first_source.decode("ascii"),
        "last_source_timestamp_fixed_est": last_source.decode("ascii"),
        **{key: stats[key] for key in ("archive_rows", "coherent_rows", "incoherent_rows",
                                      "rows_sharing_previous_timestamp", "zero_spread_rows")},
    })


def scheduled_hours():
    first = date.fromisoformat(PROTOCOL["utc_first_date_inclusive"])
    last = date.fromisoformat(PROTOCOL["utc_last_date_inclusive"])
    starts = []
    for offset in range((last - first).days + 1):
        day = first + timedelta(days=offset)
        if day.weekday() < 5:
            starts.extend(date_ms(day) + hh * HOUR_MS for hh in range(24))
    assert len(starts) == PROTOCOL["scheduled_hours"]
    return starts


def quote_record(quote):
    if quote is None:
        return None
    return {
        "time_ms": quote.time_ms, "time_utc": utc_text(quote.time_ms), "source_row": quote.source_row,
        "bid": price_text(quote.bid_points), "ask": price_text(quote.ask_points),
        "bid_points": quote.bid_points, "ask_points": quote.ask_points,
    }


def assess_hour(start, quotes):
    expiry = start + WINDOW_MS
    row = {
        "hour_start_ms": start, "hour_start_utc": utc_text(start), "expiry_ms": expiry,
        "expiry_utc": utc_text(expiry), "quote_rows": len(quotes), "status": "skipped_no_reference",
        "levels": None, "reference": None, "trigger": None, "eligibility": None,
        "trigger_overshoot_points": None, "bid_below_stop_at_trigger": None,
        "reference_to_trigger_ms": None, "activation_to_limit_wait_ms": None,
    }
    if not quotes or quotes[0].time_ms >= start + REFERENCE_MS:
        return row, None, None
    ref = quotes[0]
    stop = ref.ask_points + STOP_OFFSET
    limit = stop - LIMIT_OFFSET
    row.update(status="no_trigger", reference=quote_record(ref), levels={
        "reference_ask": price_text(ref.ask_points), "stop": price_text(stop), "limit": price_text(limit),
        "reference_ask_points": ref.ask_points, "stop_points": stop, "limit_points": limit,
    })
    trigger_index = next((i for i in range(1, len(quotes)) if quotes[i].ask_points >= stop), None)
    if trigger_index is None:
        return row, None, None
    trigger = quotes[trigger_index]
    limit_index = next((i for i in range(trigger_index + 1, len(quotes)) if quotes[i].ask_points <= limit), None)
    eligible = quotes[limit_index] if limit_index is not None else None
    row.update(
        status="limit_eligible" if eligible else "limit_expired",
        trigger=quote_record(trigger), eligibility=quote_record(eligible),
        trigger_overshoot_points=trigger.ask_points - stop,
        bid_below_stop_at_trigger=trigger.bid_points < stop,
        reference_to_trigger_ms=trigger.time_ms - ref.time_ms,
        activation_to_limit_wait_ms=(eligible.time_ms - trigger.time_ms) if eligible else None,
    )
    return row, trigger_index, limit_index


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


def minute_bars(start, quotes):
    minutes = [[] for _ in range(WINDOW_MS // MINUTE_MS)]
    for quote in quotes:
        minutes[(quote.time_ms - start) // MINUTE_MS].append(quote)
    return [{
        "time_ms": start + i * MINUTE_MS, "time_utc": utc_text(start + i * MINUTE_MS),
        "minute_index": i, "quote_rows": len(children),
        "bid": candle([q.bid_points for q in children]), "ask": candle([q.ask_points for q in children]),
    } for i, children in enumerate(minutes)]


def quote_window(quotes, center, event, event_indices):
    if center is None:
        return None
    anchor = quotes[center]
    start, end = max(0, center - QUOTE_RADIUS), min(len(quotes), center + QUOTE_RADIUS + 1)
    return {
        "event": event, "center": quote_record(anchor), "radius_rows_requested": QUOTE_RADIUS,
        "before_count": center - start, "after_count": end - center - 1,
        "rows": [quote_record(quotes[i]) | {
            "offset_ms": quotes[i].time_ms - anchor.time_ms, "offset_rows": i - center,
            "event": event_indices.get(i),
        } for i in range(start, end)],
    }


def chart_case(hour, quotes, trigger_index, limit_index):
    indices = {0: "reference", trigger_index: "trigger"}
    if limit_index is not None:
        indices[limit_index] = "eligibility"
    after = quotes[trigger_index + 1:]
    return {
        "selection": "earliest_" + hour["status"], "hour": hour,
        "m1": minute_bars(hour["hour_start_ms"], quotes),
        "quote_windows": {
            "trigger": quote_window(quotes, trigger_index, "trigger", indices),
            "eligibility": quote_window(quotes, limit_index, "eligibility", indices),
        },
        "post_trigger": {
            "quote_rows": len(after),
            "lowest_ask": quote_record(min(after, key=lambda q: q.ask_points, default=None)),
            "lowest_bid": quote_record(min(after, key=lambda q: q.bid_points, default=None)),
        },
    }


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


def summarize(hours):
    statuses = Counter(hour["status"] for hour in hours)
    triggered = [hour for hour in hours if hour["trigger"]]
    eligible = [hour for hour in hours if hour["eligibility"]]
    skipped_empty = sum(hour["status"] == "skipped_no_reference" and not hour["quote_rows"] for hour in hours)
    skipped = statuses["skipped_no_reference"]
    bid_below = sum(hour["bid_below_stop_at_trigger"] for hour in triggered)
    assert len(eligible) == statuses["limit_eligible"]
    assert len(triggered) == statuses["limit_eligible"] + statuses["limit_expired"]
    return {
        "scheduled_hours": len(hours), "reference_hours": len(hours) - skipped, "skipped_hours": skipped,
        "skipped_empty_window": skipped_empty, "skipped_opening_minute_only": skipped - skipped_empty,
        "not_activated_hours": statuses["no_trigger"], "activated_hours": len(triggered),
        "eligible_hours": len(eligible), "activated_expired_hours": statuses["limit_expired"],
        "bid_below_stop_at_activation_hours": bid_below,
        "bid_at_or_above_stop_at_activation_hours": len(triggered) - bid_below,
        "records_in_scheduled_half_hours": sum(hour["quote_rows"] for hour in hours),
        "records_in_reference_half_hours": sum(hour["quote_rows"] for hour in hours if hour["reference"]),
        "trigger_overshoot_points": time_summary([hour["trigger_overshoot_points"] for hour in triggered]),
        "limit_wait_ms": time_summary([hour["activation_to_limit_wait_ms"] for hour in eligible]),
    }


def compute(archive):
    starts = scheduled_hours()
    hours, cases, validation = [], {}, {}
    current = []

    def settle(start):
        hour, trigger, eligible = assess_hour(start, current)
        hours.append(hour)
        status = hour["status"]
        if status in CASE_ORDER and status not in cases:
            cases[status] = chart_case(hour, current, trigger, eligible)
        current.clear()

    index = 0
    for quote in read_quotes(archive, validation):
        while index < len(starts) and quote.time_ms >= starts[index] + WINDOW_MS:
            settle(starts[index])
            index += 1
        if index < len(starts) and quote.time_ms >= starts[index]:
            current.append(quote)
    while index < len(starts):
        settle(starts[index])
        index += 1
    assert len(hours) == len(starts)
    return {
        "protocol": PROTOCOL, "protocol_sha256": PROTOCOL_SHA, "archive": ARCHIVE,
        "validation": validation, "summary": summarize(hours), "hours": hours,
        "cases": [cases[kind] for kind in CASE_ORDER if kind 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("--output", type=Path, default=here / "evidence.json")
    args = parser.parse_args()
    assert sha256(PROTOCOL_UTF8.encode("utf-8")).hexdigest() == PROTOCOL_SHA
    frozen = here / "protocol.json"
    if frozen.exists():
        assert frozen.read_bytes() == PROTOCOL_UTF8.encode("utf-8")
    evidence = compute(args.archive)
    args.output.write_text(json.dumps(evidence, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8")
    summary = {key: value for key, value in evidence["summary"].items() if not isinstance(value, dict)}
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()
