"""The declared change in CHANGES-r2.md: a slice load that re-reads its last day, 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 (the control, which must end exactly as round 1's no-outage arm
did), the change feed (a second control) and time partitions with a trailing re-read of the last day. Writes
<out>/trailing_reread.json and prints a verdict line; the result is written only when both controls match.

Usage: python3 -B tools/trailing_reread.py data/source-log.jsonl.gz results/summary.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
from contract import aliases  # noqa: E402

DAY_MILLIS = 24 * 60 * 60 * 1000


class TrailingPartitions(TimePartitions):
    """Time partitions that, on each run, delete and re-load every slice in the day before the newly closed one."""
    name = "time_partitions_reread_1d"

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


def main():
    log, summary_path, out, work = sys.argv[1:5]
    summary = json.load(open(summary_path, encoding="utf-8"))["designs"]
    if os.path.exists(work):
        shutil.rmtree(work)
    os.makedirs(work)
    os.makedirs(out, exist_ok=True)
    designs = {"time_partitions": TimePartitions(), "change_feed": ChangeFeed(),
               "time_partitions_reread_1d": TrailingPartitions()}
    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 = {}
    seen, late_days = set(), []  # hours from origin to first appearance, for new events that are not re-keys
    for meta, rows in load_log(log):
        view, truth, now = ReplayView(meta, rows), Truth(rows), iso_ms(meta["fetched_utc"])
        for i, r in truth.live.items():
            if i not in seen and prev_now is not None and not any(a in seen for a in aliases(r) if a != i):
                late_days.append((now - r["time"]) / DAY_MILLIS)
        seen.update(truth.live)
        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, ids_by)
        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][0].get(k, 0) for k in keep}
    tp, cf = summary["time_partitions"], summary["change_feed"]
    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"],
    }
    ok = all(control.values())
    rr = res["time_partitions_reread_1d"]
    tp_wrong_ids = {i for c, v in last["time_partitions"][1].items() for i in v}
    rr_wrong_ids = {i for c, v in last["time_partitions_reread_1d"][1].items() for i in v}
    result = {
        "declared_in": "CHANGES-r2.md", "label": "added after the results",
        "control": control,
        "reread_1d": {"last": rr["last"], "wrong_series": rr["wrong_series"],
                      "bytes_read_after_initial": rr["bytes_after_initial"], "runs_after_initial": rr["runs_after_initial"],
                      "bytes_vs_full_after_initial": round(rr["bytes_after_initial"] / full_bytes_after_initial, 6),
                      "times_change_feed": round(rr["bytes_after_initial"] / res["change_feed"]["bytes_after_initial"], 1),
                      "of_slice_table_wrong_still_wrong": len(tp_wrong_ids & rr_wrong_ids),
                      "slice_table_wrong_ids": len(tp_wrong_ids),
                      "example_ids": {c: v[:5] for c, v in last["time_partitions_reread_1d"][1].items() if v}},
        "new_events": {"after_first_read": len(late_days),
                       "first_seen_more_than_1_day_after_origin": sum(1 for d in late_days if d > 1),
                       "median_days_origin_to_first_seen": round(sorted(late_days)[len(late_days) // 2], 2)},
        "predictions": {
            "Q1": {"text": "ends with at least 1 and fewer than 53 wrong rows",
                   "observed": rr["last"]["wrong"], "held": 1 <= rr["last"]["wrong"] < 53},
            "Q2": {"text": "reads between 5 and 30 times the change feed's data per run after the first load",
                   "observed": round(rr["bytes_after_initial"] / res["change_feed"]["bytes_after_initial"], 1),
                   "held": 5 <= rr["bytes_after_initial"] / res["change_feed"]["bytes_after_initial"] <= 30}},
    }
    if ok:
        path = os.path.join(out, "trailing_reread.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, "reread_1d_last": rr["last"], "new_events": result["new_events"],
                      "times_change_feed": result["reread_1d"]["times_change_feed"],
                      "still_wrong_of_slice": result["reread_1d"]["of_slice_table_wrong_still_wrong"]}))
    print("VERDICT:", "PASS" if ok else "FAIL control mismatch, nothing written")


if __name__ == "__main__":
    main()
