"""The declared change in CHANGES-r3.md: slice loads that re-read their last 3 and last 7 days, replayed over the recorded reads.

Runs, over the same recorded reads and with the same source rules and scoring as round 1, without the scheduler and
without planted read failures: plain time partitions and the change feed (controls, which must end as round 1's
no-outage arm did), the 1-day re-read (a control, which must end as results/trailing_reread.json reports) and the
3-day and 7-day re-reads. Writes <out>/trailing_windows.json and prints a verdict line; the result is written only
when every control matches.

Usage: python3 -B tools/trailing_windows.py data/source-log.jsonl.gz results/summary.json results/trailing_reread.json <out dir> <work dir>
"""
import json
import os
import shutil
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

from designs import SETTLE_MILLIS, ChangeFeed, Design, TimePartitions, connect, table_rows  # noqa: E402
from replay import ReplayView, iso_ms, load_log  # noqa: E402
from score import Truth, compare  # noqa: E402

DAY_MILLIS = 24 * 60 * 60 * 1000


def trailing(days):
    class Trailing(TimePartitions):
        """Time partitions that, on each run, delete and re-load every slice in the days before the newly closed one."""
        name = f"time_partitions_reread_{days}d"

        def run(self, db, view, tick, partition=None):
            lo, hi = partition
            return super().run(db, view, tick, partition=(hi - days * DAY_MILLIS, hi))
    return Trailing()


def main():
    log, summary_path, one_day_path, out, work = sys.argv[1:6]
    summary = json.load(open(summary_path, encoding="utf-8"))["designs"]
    one_day = json.load(open(one_day_path, encoding="utf-8"))["reread_1d"]
    if os.path.exists(work):
        shutil.rmtree(work)
    os.makedirs(work)
    os.makedirs(out, exist_ok=True)
    designs = {"time_partitions": TimePartitions(), "change_feed": ChangeFeed()}
    for days in (1, 3, 7):
        designs[f"time_partitions_reread_{days}d"] = trailing(days)
    dbs = {n: connect(os.path.join(work, n + ".duckdb")) for n in designs}
    res = {n: {"wrong_series": [], "bytes_after_initial": 0, "runs_after_initial": 0} for n in designs}
    full_bytes_after_initial = 0
    prev_now = None
    last = {}
    for meta, rows in load_log(log):
        view, truth, now = ReplayView(meta, rows), Truth(rows), iso_ms(meta["fetched_utc"])
        for n, d in designs.items():
            db = dbs[n]
            if prev_now is None:
                Design.initial(d, db, view, meta["tick"])
            else:
                st = d.run(db, view, meta["tick"], partition=(prev_now - SETTLE_MILLIS, now - SETTLE_MILLIS))
                res[n]["bytes_after_initial"] += st["bytes_read"]
                res[n]["runs_after_initial"] += 1
            errs, ids_by = compare(table_rows(db), truth)
            res[n]["wrong_series"].append(errs["wrong"])
            last[n] = errs
        if prev_now is not None:
            full_bytes_after_initial += view.query()[1]
        prev_now = now
    for db in dbs.values():
        db.close()
    keep = ("stale", "missing", "old_key", "deleted_kept", "vanished", "repeat", "wrong", "live", "table_rows")
    for n in designs:
        res[n]["last"] = {k: last[n].get(k, 0) for k in keep}
    tp, cf, r1 = summary["time_partitions"], summary["change_feed"], res["time_partitions_reread_1d"]
    control = {
        "time_partitions_last_matches": all(res["time_partitions"]["last"][k] == tp["last"].get(k, 0) for k in keep),
        "time_partitions_series_matches": res["time_partitions"]["wrong_series"] == tp["wrong_series"],
        "time_partitions_bytes_match": res["time_partitions"]["bytes_after_initial"] == tp["bytes_read_after_initial"],
        "change_feed_series_matches": res["change_feed"]["wrong_series"] == cf["wrong_series"],
        "change_feed_bytes_match": res["change_feed"]["bytes_after_initial"] == cf["bytes_read_after_initial"],
        "full_reload_bytes_match": full_bytes_after_initial == summary["full_reload"]["bytes_read_after_initial"],
        "reread_1d_last_matches": all(r1["last"][k] == one_day["last"].get(k, 0) for k in keep),
        "reread_1d_bytes_match": r1["bytes_after_initial"] == one_day["bytes_read_after_initial"],
    }
    ok = all(control.values())
    cf_bytes = res["change_feed"]["bytes_after_initial"]
    windows = {}
    for days in (3, 7):
        r = res[f"time_partitions_reread_{days}d"]
        windows[f"{days}d"] = {"last": r["last"], "wrong_series": r["wrong_series"],
                               "bytes_read_after_initial": r["bytes_after_initial"],
                               "runs_after_initial": r["runs_after_initial"],
                               "bytes_vs_full_after_initial": round(r["bytes_after_initial"] / full_bytes_after_initial, 6),
                               "times_change_feed": round(r["bytes_after_initial"] / cf_bytes, 1)}
    w3, w7 = windows["3d"], windows["7d"]
    result = {
        "declared_in": "CHANGES-r3.md", "label": "added after the results",
        "control": control,
        "windows": windows,
        "predictions": {
            "Q3": {"text": "the 3-day re-read ends with at least 1 wrong row",
                   "observed": w3["last"]["wrong"], "held": w3["last"]["wrong"] >= 1},
            "Q4": {"text": "the 7-day re-read ends with at least 1 wrong row",
                   "observed": w7["last"]["wrong"], "held": w7["last"]["wrong"] >= 1},
            "Q5": {"text": "the 7-day re-read reads between 20 and 120 times the change feed's data per run after the first load",
                   "observed": w7["times_change_feed"],
                   "held": 20 <= w7["bytes_read_after_initial"] / cf_bytes <= 120}},
    }
    if ok:
        path = os.path.join(out, "trailing_windows.json")
        with open(path + ".tmp", "w", encoding="utf-8") as f:
            json.dump(result, f, indent=1)
            f.write("\n")
        os.replace(path + ".tmp", path)
    print(json.dumps({"control": control, "3d": w3["last"], "3d_times_cf": w3["times_change_feed"],
                      "7d": w7["last"], "7d_times_cf": w7["times_change_feed"]}))
    print("VERDICT:", "PASS" if ok else "FAIL control mismatch, nothing written")


if __name__ == "__main__":
    main()
