#!/usr/bin/env python3
"""Rebuild the frozen EUR/USD Bid/Ask double-bottom evidence."""
import argparse
from array import array
from bisect import bisect_left, bisect_right
from calendar import monthrange
from collections import Counter
from concurrent.futures import ProcessPoolExecutor
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal, localcontext
from fractions import Fraction
from hashlib import file_digest, sha256
import json
from pathlib import Path
from typing import NamedTuple
from zipfile import ZipFile

PINNED_PROTOCOL = "c226e25238f80e73a0eb448dbb419bfdd2f2abf2a9e5599a8130c5fa3d11fc72"
PINNED_ARCHIVES = json.loads(r'''[
  {
    "period": "2024-07",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/7",
    "member": "DAT_ASCII_EURUSD_T_202407.csv",
    "member_bytes": 57086289,
    "member_crc32": "7cd97dc3",
    "bytes": 8641917,
    "sha256": "d46ff671cd5fd65c605d7c03496217dcbca3ed39086dc3afe202f193f518442c"
  },
  {
    "period": "2024-08",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/8",
    "member": "DAT_ASCII_EURUSD_T_202408.csv",
    "member_bytes": 71768892,
    "member_crc32": "c315681c",
    "bytes": 10855541,
    "sha256": "89d4922aab8b3e83f10d8c9635f4e247652e8c0c1f7dcda306cbf83fc4b2751a"
  },
  {
    "period": "2024-09",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/9",
    "member": "DAT_ASCII_EURUSD_T_202409.csv",
    "member_bytes": 70395156,
    "member_crc32": "6d2c66cf",
    "bytes": 10645505,
    "sha256": "00ab61749d1d70081c18f9dfe4a175e160c54de29edb779a713432fcbae10059"
  },
  {
    "period": "2024-10",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/10",
    "member": "DAT_ASCII_EURUSD_T_202410.csv",
    "member_bytes": 69110925,
    "member_crc32": "1c3f8ed7",
    "bytes": 10424525,
    "sha256": "5041948a91b7c3ab6036c08c5adfbe2438c7c3d21ff7ccdaafbc8d61f18d039d"
  },
  {
    "period": "2024-11",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/11",
    "member": "DAT_ASCII_EURUSD_T_202411.csv",
    "member_bytes": 90198147,
    "member_crc32": "797a3c7e",
    "bytes": 13936558,
    "sha256": "2ca378fffe3fcaee698ef2486e6407d72afd8f292002983463c338f329838f17"
  },
  {
    "period": "2024-12",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2024/12",
    "member": "DAT_ASCII_EURUSD_T_202412.csv",
    "member_bytes": 77216100,
    "member_crc32": "9dc0007f",
    "bytes": 11965057,
    "sha256": "a4dd430ed823a7671dd012faff1eda56f46a7cc54dd7bdb5cd5dc19db3eda3c5"
  },
  {
    "period": "2025-01",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2025/1",
    "member": "DAT_ASCII_EURUSD_T_202501.csv",
    "member_bytes": 89046321,
    "member_crc32": "7fe7ae8e",
    "bytes": 13954937,
    "sha256": "159f906f8055f6ee835d95806cf7fdf4023b6e3ef098aa308d2ab6ce53ac964a"
  },
  {
    "period": "2025-02",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2025/2",
    "member": "DAT_ASCII_EURUSD_T_202502.csv",
    "member_bytes": 80077023,
    "member_crc32": "a73fe294",
    "bytes": 12807066,
    "sha256": "63c3b2717c024f7aada8642b38e7a944646dbe2440303632918e5c594db2313e"
  },
  {
    "period": "2025-03",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2025/3",
    "member": "DAT_ASCII_EURUSD_T_202503.csv",
    "member_bytes": 91780260,
    "member_crc32": "8af5a2cb",
    "bytes": 14829874,
    "sha256": "0746c04af3a4aba26a559d0bbd665bbeda8e237c624b51625e63bf10066cc096"
  },
  {
    "period": "2025-04",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2025/4",
    "member": "DAT_ASCII_EURUSD_T_202504.csv",
    "member_bytes": 152762142,
    "member_crc32": "603e67e1",
    "bytes": 25044669,
    "sha256": "613aa42d654e66853ec35d233a372adf66d818614a2ebe9f92be4add59f7970e"
  },
  {
    "period": "2025-05",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2025/5",
    "member": "DAT_ASCII_EURUSD_T_202505.csv",
    "member_bytes": 94076892,
    "member_crc32": "bfedb4d8",
    "bytes": 15469791,
    "sha256": "3ce49d7b44e8b17c942ad2d5e77e317c023a5884f090c086806b888dae633f77"
  },
  {
    "period": "2025-06",
    "source": "https://www.histdata.com/download-free-forex-historical-data/?/ascii/tick-data-quotes/EURUSD/2025/6",
    "member": "DAT_ASCII_EURUSD_T_202506.csv",
    "member_bytes": 79729377,
    "member_crc32": "a7a40ac6",
    "bytes": 13103978,
    "sha256": "a36a057d0afcb38e11cab1bec01c4e6de83f053530e0ea99c88acf99145af77c"
  }
]''')
MS = 1000
MIN = 60 * MS
HOUR = 60 * MIN
DAY = 24 * HOUR
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
POINT_SCALE = 100_000
ARMS = ("breakout", "retest")


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


def price(points):
    return f"{points // POINT_SCALE}.{points % POINT_SCALE:05d}"


def decimal(value):
    if value is None:
        return None
    with localcontext() as ctx:
        ctx.prec = 44
        number = Decimal(value.numerator) / Decimal(value.denominator)
        return format(number.quantize(Decimal("0.000000000001")).normalize(), "f") if number else "0"


def day_number(d):
    return (d - EPOCH.date()).days


def date_string(day):
    return (EPOCH.date() + timedelta(days=day)).isoformat()


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

    def record(self, i):
        return {"time_ms": self.time[i], "utc": utc(self.time[i]), "source_row": self.row[i],
                "bid_points": self.bid[i], "ask_points": self.ask[i], "spread_points": self.ask[i]-self.bid[i],
                "bid": price(self.bid[i]), "ask": price(self.ask[i])}


def tape():
    return Tape(array("q"), array("i"), array("i"), array("i"))


def read_archive(raw, pin, protocol):
    filename = f"EURUSD-{pin['period']}.zip"
    path = raw / filename
    if path.stat().st_size != pin["bytes"]:
        raise ValueError(f"Unexpected ZIP size: {path}")
    with path.open("rb") as stream:
        if file_digest(stream, "sha256").hexdigest() != pin["sha256"]:
            raise ValueError(f"SHA-256 mismatch: {path}")
    start = protocol["session"]["start_utc_hour"] * HOUR
    end = protocol["session"]["end_utc_hour"] * HOUR
    shift = -protocol["source"]["source_utc_offset_hours"] * HOUR
    by_day = {}
    excluded = set()
    first = previous = None
    rows = ties = backwards = 0
    csv_hash = sha256()
    local_key = None
    selected_month = pin["period"].replace("-", "").encode()
    with ZipFile(path) as archive:
        info = archive.getinfo(pin["member"])
        if (info.file_size, f"{info.CRC:08x}") != (pin["member_bytes"], pin["member_crc32"]):
            raise ValueError(f"CSV identity/CRC mismatch: {path}")
        with archive.open(info) as stream:
            for rows, line in enumerate(stream, 1):
                csv_hash.update(line)
                stamp, bid_str, ask_str, _ = line.split(b",")
                if stamp[:8] != local_key:
                    local_key = stamp[:8]
                    assert local_key[:6] == selected_month, (path, local_key)
                    d = date(int(local_key[:4]), int(local_key[4:6]), int(local_key[6:8]))
                    midnight = day_number(d) * DAY + shift
                h, m, s, 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" " and 0 <= h < 24 and 0 <= m < 60 and 0 <= s < 60
                t = midnight + h * HOUR + m * MIN + s * MS + ms
                bid, bid_extra = divmod(int(bid_str.replace(b".", b"")), 10)
                ask, ask_extra = divmod(int(ask_str.replace(b".", b"")), 10)
                if bid_str[-7:-6] != b"." or ask_str[-7:-6] != b"." or bid_extra or ask_extra or not 0 < bid <= ask:
                    raise ValueError(f"Off-grid or incoherent quote in {path} at line {rows}")
                if first is None:
                    first = t
                elif t < previous:
                    backwards += 1
                    excluded.update((t//DAY, previous//DAY))
                ties += t == previous
                previous = t
                day, offset = divmod(t, DAY)
                if start <= offset < end:
                    if day not in by_day:
                        by_day[day] = tape()
                    ticks = by_day[day]
                    ticks.time.append(t)
                    ticks.bid.append(bid)
                    ticks.ask.append(ask)
                    ticks.row.append(rows)
    assert rows > 0
    return by_day, excluded, {**pin, "file": filename, "rows": rows, "csv_sha256": csv_hash.hexdigest(),
                              "first_ms": first, "last_ms": previous, "equal_timestamp_rows": ties,
                              "backward_steps": backwards, "quarantined_dates": sorted(map(date_string, excluded))}


def candles(ticks, begin, end, width):
    i = 0
    bars = []
    for t in range(begin, end, width):
        j = bisect_left(ticks.time, t+width, i)
        if j == i:
            bars.append(None)
        else:
            def ohlc(side):
                values = side[i:j]
                return {"open": values[0], "high": max(values), "low": min(values), "close": values[-1]}
            bars.append({"open_ms": t, "utc": utc(t), "close_ms": t+width,
                         "bid": ohlc(ticks.bid), "ask": ohlc(ticks.ask), "quote_count": j-i})
        i = j
    return bars


def select_pattern(bars, day_start, protocol):
    g = protocol["geometry"]
    n = g["swing_neighbors_each_side"]
    h, m = map(int, protocol["session"]["last_breakout_close_utc"].split(":"))
    cutoff = day_start + h*HOUR + m*MIN
    prior = pending = None
    for i in range(2*n, len(bars)):
        current = bars[i]
        if current["close_ms"] > cutoff:
            break
        p = i - n
        low = bars[p]["bid"]["low"]
        if all(low < bars[j]["bid"]["low"] for j in range(p-n,p+n+1) if j != p):
            if prior is not None and g["pivot_gap_min_bars"] <= p-prior <= g["pivot_gap_max_bars"]:
                first_low = bars[prior]["bid"]["low"]
                neckline = max(bars[j]["bid"]["high"] for j in range(prior+1,p))
                height = neckline - max(first_low, low)
                if abs(first_low-low) <= g["bottom_difference_max_points"] and height >= g["height_min_points"]:
                    pending = {"p1": prior, "p2": p, "p1_ms": bars[prior]["open_ms"], "p2_ms": bars[p]["open_ms"],
                               "p1_low": first_low, "p2_low": low, "confirmed_ms": current["close_ms"],
                               "neckline": neckline, "height": height, "stop": min(first_low,low)-g["stop_below_lower_bottom_points"],
                               "target": neckline+height}
            prior = p
        if pending is None:
            continue
        if i > pending["p2"]+g["breakout_through_bars_after_second"] or current["bid"]["low"] <= pending["stop"]:
            pending = None
        elif bars[i-1]["bid"]["close"] <= pending["neckline"] < current["bid"]["close"]:
            return {**pending, "breakout_index": i, "breakout_ms": current["close_ms"],
                    "breakout_bid_close": current["bid"]["close"]}
    return None


def first_quote(ticks, decision, wait):
    i = bisect_left(ticks.time, decision)
    return i if i < len(ticks.time) and ticks.time[i] <= decision+wait else None


def execute(ticks, signal, decision, i, protocol):
    cfg = protocol["execution"]
    result = {"decision_ms": decision}
    if i is None:
        return {**result, "status": "first_quote_missing"}
    q = ticks.record(i)
    result["first_quote"] = q
    bid, ask = q["bid_points"], q["ask_points"]
    stop, target = signal["stop"], signal["target"]
    extra = cfg["adverse_points_per_side"]
    if not stop < bid < target:
        return {**result, "status": "first_quote_level"}
    if ask-bid > cfg["spread_max_points"]:
        return {**result, "status": "spread_cap"}
    if ask+extra >= target:
        return {**result, "status": "target_room"}
    result.update(entry=q, risk_points=ask-stop)
    deadline = signal["breakout_ms"] + cfg["deadline_minutes_after_breakout"]*MIN
    gap_limit = cfg["quote_gap_max_seconds"]*MS
    allowed = cfg["first_quote_max_seconds"]*MS
    previous = ticks.time[i]
    for j in range(i+1,len(ticks.time)):
        t, b = ticks.time[j], ticks.bid[j]
        if t-previous > gap_limit or t > deadline+allowed:
            break
        reason = "time" if t >= deadline else "stop" if b <= stop else "target" if b >= target else None
        if reason is not None:
            return {**result, "status": "completed", "exit_reason": reason, "exit": ticks.record(j),
                    "net_points": b-ask-2*extra, "gross_points": b-ask, "stress_points": b-ask-4*extra}
        previous = t
    return {**result, "status": "exit_unavailable"}


def try_retest(bars, ticks, signal, protocol):
    cfg = protocol["execution"]
    line = signal["neckline"]
    start = signal["breakout_ms"]
    expiry = start + cfg["retest_minutes"]*MIN
    q_wait = cfg["first_quote_max_seconds"]*MS
    max_gap = cfg["quote_gap_max_seconds"]*MS
    bar = next((bar for bar in bars[signal["breakout_index"]+1:]
                if bar["close_ms"] <= expiry and bar["bid"]["low"] <= line < bar["bid"]["close"]), None)
    selected_quote = first_quote(ticks, bar["close_ms"], q_wait) if bar is not None else None
    if bar is None:
        through = expiry
        stop_index = bisect_left(ticks.time, through)
    elif selected_quote is None:
        through = bar["close_ms"]+q_wait
        stop_index = bisect_right(ticks.time, through)
    else:
        through = ticks.time[selected_quote]
        stop_index = selected_quote+1
    previous = start
    previous_outcome = {"retest_close_ms": bar["close_ms"] if bar is not None else None}
    for j in range(bisect_left(ticks.time, start),stop_index):
        t,b = ticks.time[j],ticks.bid[j]
        if t-previous > max_gap:
            return {**previous_outcome, "status": "retest_gap", "event": ticks.record(j)}
        if b <= signal["stop"] or b >= signal["target"]:
            return {**previous_outcome, "status": "retest_stop" if b <= signal["stop"] else "retest_target",
                    "event": ticks.record(j)}
        previous = t
    if through-previous > max_gap:
        return {**previous_outcome, "status": "retest_gap"}
    if bar is None:
        return {**previous_outcome, "status": "retest_window_expired"}
    return {**previous_outcome, **execute(ticks, signal, bar["close_ms"], selected_quote, protocol)}


def quote_excerpt(ticks, at, actual):
    start = max(0, bisect_left(ticks.time,at)-4)
    stop = min(start+14, len(ticks.time))
    return [{"marked": ticks.row[i] == actual, **ticks.record(i)} for i in range(start,stop)]


def snapshot(signal, bars, ticks, protocol):
    deadline = signal["breakout_ms"]+protocol["execution"]["deadline_minutes_after_breakout"]*MIN
    chart = [b for b in bars[max(0,signal["p1"]-2):] if b["open_ms"] <= deadline]
    views = {}
    for arm in ARMS:
        row = signal[arm]
        event = row.get("entry") or row.get("event") or row.get("first_quote")
        if event is not None:
            views[arm] = quote_excerpt(ticks,event["time_ms"],event["source_row"])
    return {"signal": signal, "m15": chart, "quote_views": views}


def run_month(args):
    raw,pin,protocol = args
    by_day, excluded, provenance = read_archive(raw, pin, protocol)
    y,m = map(int,pin["period"].split("-"))
    start = day_number(date(y,m,1))
    sec = protocol["session"]
    width = protocol["geometry"]["bar_minutes"]*MIN
    complete = 0
    missing = []
    signals = []
    captures = []
    first_period_end = protocol["periods"]["development"][1]
    period = "development" if pin["period"] < first_period_end[:7] else "holdout"
    for day in range(start,start+monthrange(y,m)[1]):
        if (day+3)%7 >= 5:
            continue
        label = date_string(day)
        if day in excluded:
            missing.append({"date": label, "reason": "timestamp_backstep"})
            continue
        ticks = by_day.get(day)
        if ticks is None:
            missing.append({"date": label, "reason": "no_quotes"})
            continue
        bars = candles(ticks,day*DAY+sec["start_utc_hour"]*HOUR,day*DAY+sec["end_utc_hour"]*HOUR,width)
        if any(bar is None for bar in bars):
            missing.append({"date": label, "reason": "incomplete_m15", "missing_bars": bars.count(None)})
            continue
        complete += 1
        selected = select_pattern(bars,day*DAY,protocol)
        if selected is None:
            continue
        i = first_quote(ticks, selected["breakout_ms"], protocol["execution"]["first_quote_max_seconds"]*MS)
        signal = {"date": label, "period": period, **selected,
                  "breakout": execute(ticks,selected,selected["breakout_ms"],i,protocol),
                  "retest": try_retest(bars,ticks,selected,protocol)}
        signals.append(signal)
        if period == "holdout":
            captures.append(snapshot(signal,bars,ticks,protocol))
    return {"source": provenance, "complete_sessions": complete, "incomplete_sessions": missing,
            "signals": signals, "captures": captures}


def arm_stats(rows):
    entered = [row for row in rows if "entry" in row]
    closed = [row for row in rows if row["status"] == "completed"]
    n = len(closed)
    values = {k:sum(Fraction(row[k],row["risk_points"]) for row in closed)
              for k in ("net_points","gross_points","stress_points")}
    equity = peak = drawdown = Fraction(0)
    for row in closed:
        equity += Fraction(row["net_points"],row["risk_points"])
        peak = max(peak,equity)
        drawdown = max(drawdown,peak-equity)
    return {"entered": len(entered), "completed": n, "wins": sum(r["net_points"] > 0 for r in closed),
            "net_r": decimal(values["net_points"]), "mean_r": decimal(values["net_points"]/n if n else None),
            "gross_r": decimal(values["gross_points"]), "stress_r": decimal(values["stress_points"]),
            "max_drawdown_r": decimal(drawdown),
            "net_pips": decimal(Fraction(sum(r["net_points"] for r in closed),10)),
            "mean_spread_pips": decimal(Fraction(sum(r["entry"]["spread_points"] for r in entered),10*len(entered)) if entered else None),
            "states": dict(Counter(r["status"] for r in rows)), "exit_reasons": dict(Counter(r["exit_reason"] for r in closed))}


def summarize(signals):
    paired = [r for r in signals if all(r[a]["status"] == "completed" for a in ARMS)]
    return {"signals": len(signals), **{a:arm_stats([r[a] for r in signals]) for a in ARMS},
            "paired":{"signals": len(paired), **{a:arm_stats([r[a] for r in paired]) for a in ARMS}}}


def choose_examples(captures):
    selectors = (
        ("both", lambda r:r["breakout"]["status"]=="completed" and r["retest"]["status"]=="completed"),
        ("expired", lambda r:r["breakout"]["status"]=="completed" and r["retest"]["status"]=="retest_window_expired"),
        ("canceled", lambda r:r["breakout"]["status"]=="completed" and r["retest"]["status"] in ("retest_stop","retest_target")),
    )
    used = set()
    examples = []
    for kind,select in selectors:
        available = [c for c in captures if c["signal"]["date"] not in used]
        matching = next((c for c in available if select(c["signal"])),None)
        fallback = next((c for c in available if c["signal"]["breakout"]["status"]=="completed"
                         and "entry" not in c["signal"]["retest"]), available[0] if available else None)
        example = matching or fallback
        if example is not None:
            used.add(example["signal"]["date"])
            examples.append({"kind": kind, "exact_category": matching is not None, **example})
    return examples


def replay(raw, protocol_bytes, jobs):
    digest = sha256(protocol_bytes).hexdigest()
    if digest != PINNED_PROTOCOL:
        raise ValueError("Protocol bytes do not match the frozen study.")
    protocol = json.loads(protocol_bytes)
    inputs = [(raw,pin,protocol) for pin in PINNED_ARCHIVES]
    if jobs == 1:
        monthly = list(map(run_month,inputs))
    else:
        with ProcessPoolExecutor(max_workers=jobs) as pool:
            monthly = list(pool.map(run_month,inputs))
    sources = [m["source"] for m in monthly]
    assert all(a["last_ms"] <= b["first_ms"] for a,b in zip(sources,sources[1:]))
    signals = [r for m in monthly for r in m["signals"]]
    captures = [c for m in monthly for c in m["captures"]]
    coverage = {"quote_rows": sum(s["rows"] for s in sources),
                "complete_sessions": sum(m["complete_sessions"] for m in monthly),
                "incomplete_sessions": [d for m in monthly for d in m["incomplete_sessions"]]}
    return {"protocol_sha256": digest, "protocol": protocol, "sources": sources, "coverage": coverage,
            "periods": {p:summarize([r for r in signals if r["period"]==p]) for p in protocol["periods"]},
            "months": {m["source"]["period"]:summarize(m["signals"]) for m in monthly},
            "signals": signals, "examples": choose_examples(captures),
            "field_notes": {"retest_close_ms": "Earliest qualifying M15 candle close found in the archived 60-minute window. Cancellation can precede that close. decision_ms records the time at which the model reaches the entry checks."}}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--raw-dir",type=Path,required=True)
    parser.add_argument("--protocol",type=Path,required=True)
    parser.add_argument("--output",type=Path,required=True)
    parser.add_argument("--jobs",type=int,choices=(1,2,3,4,5,6),default=4)
    args = parser.parse_args()
    result = replay(args.raw_dir,args.protocol.read_bytes(),args.jobs)
    args.output.write_text(json.dumps(result,ensure_ascii=False,separators=(",",":"))+"\n",encoding="utf-8")
    print(json.dumps({"coverage":result["coverage"],"periods":result["periods"],
                      "sha256":sha256(args.output.read_bytes()).hexdigest()},ensure_ascii=False,indent=2))


if __name__=="__main__":
    main()
