"""The declared change in CHANGES-r4.md: round 1's four designs over a second recording of the same window.

Runs full reload, time partitions, incremental by updated time and the change feed, with the same source rules and
scoring as round 1, without the scheduler and without planted read failures. First over round 1's recorded reads as
the control, which must reproduce round 1's no-outage arm for all four designs (wrong rows read for read and data
read after the first load); then over the second recording. Writes <out>/second_recording.json only when the control
matches, and prints a verdict line.

Usage: python3 -B tools/second_recording.py data/source-log.jsonl.gz results/summary.json data/source-log-r4.jsonl.gz <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 MAIN, SETTLE_MILLIS, Design, connect, table_rows  # noqa: E402
from replay import ReplayView, iso_ms, load_log  # noqa: E402
from score import Truth, compare  # noqa: E402

KEEP = ("stale", "missing", "old_key", "deleted_kept", "vanished", "repeat", "duplicates", "wrong", "live", "table_rows")


def run_designs(log, work):
    """Every design from a fresh first load over one recorded log; the source's deletions and re-keys alongside."""
    if os.path.exists(work):
        shutil.rmtree(work)
    os.makedirs(work)
    designs = {n: cls() for n, cls in MAIN.items()}
    dbs = {n: connect(os.path.join(work, n + ".duckdb")) for n in designs}
    res = {n: {"wrong_series": [], "deleted_kept_series": [], "bytes_after_initial": 0, "runs_after_initial": 0}
           for n in designs}
    ever_live, origin, deleted_at, rekeyed = set(), {}, {}, set()
    prev_now, first_utc, last_utc, reads = None, None, None, 0
    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, _ = compare(table_rows(db), truth)
            res[n]["wrong_series"].append(errs["wrong"])
            res[n]["deleted_kept_series"].append(errs.get("deleted_kept", 0))
            last[n] = errs
        by_id = {r["id"]: r for r in rows if r.get("id")}
        for i in truth.deleted:
            if i in ever_live and i not in deleted_at:
                r = by_id.get(i, {})
                deleted_at[i] = {"read": reads, "minutes_after_origin":
                                 round((r["updated"] - origin[i]) / 60000) if isinstance(r.get("updated"), int) else None}
        for a in truth.alias_of:
            if a in ever_live:
                rekeyed.add(a)
        for i, r in truth.live.items():
            ever_live.add(i)
            origin.setdefault(i, r.get("time"))
        first_utc = first_utc or meta["fetched_utc"]
        last_utc = meta["fetched_utc"]
        prev_now = now
        reads += 1
    for db in dbs.values():
        db.close()
    for n in designs:
        res[n]["last"] = {k: last[n].get(k, 0) for k in KEEP}
    span_h = round((iso_ms(last_utc) - iso_ms(first_utc)) / 3600000, 2)
    source = {"reads": reads, "span_hours": span_h, "live_last": last[next(iter(designs))].get("live", 0),
              "newly_deleted": len(deleted_at), "deletions": [dict(id=i, **v) for i, v in sorted(deleted_at.items())],
              "rekeyed": len(rekeyed)}
    return res, source


def main():
    log1, summary_path, log2, out, work = sys.argv[1:6]
    summary = json.load(open(summary_path, encoding="utf-8"))["designs"]
    os.makedirs(out, exist_ok=True)
    r1, _ = run_designs(log1, os.path.join(work, "round1"))
    control = {}
    for n in MAIN:
        control[f"{n}_series_matches"] = r1[n]["wrong_series"] == summary[n]["wrong_series"]
        control[f"{n}_bytes_match"] = r1[n]["bytes_after_initial"] == summary[n]["bytes_read_after_initial"]
    ok = all(control.values())
    r2, src = run_designs(log2, os.path.join(work, "second"))
    cf_bytes = r2["change_feed"]["bytes_after_initial"]
    designs = {n: {"last": r2[n]["last"], "wrong_series": r2[n]["wrong_series"],
                   "deleted_kept_series": r2[n]["deleted_kept_series"],
                   "bytes_read_after_initial": r2[n]["bytes_after_initial"],
                   "runs_after_initial": r2[n]["runs_after_initial"],
                   "times_change_feed": round(r2[n]["bytes_after_initial"] / cf_bytes, 1) if cf_bytes else None}
               for n in MAIN}
    dk = {n: designs[n]["last"]["deleted_kept"] for n in MAIN}
    d1 = src["newly_deleted"] >= 1
    d2 = (dk["incremental_updated"] >= 1 and dk["time_partitions"] >= 1
          and dk["change_feed"] == 0 and dk["full_reload"] == 0) if d1 else None
    result = {
        "declared_in": "CHANGES-r4.md", "label": "added after the results",
        "control": control,
        "source": src,
        "designs": designs,
        "predictions": {
            "D1": {"text": "the new recording holds at least one deletion of an event that was live at an earlier read",
                   "observed": src["newly_deleted"], "held": d1},
            "D2": {"text": "if it does, incremental by updated time and time partitions each end with at least 1 deleted "
                           "event kept, and the change feed and the full reload with none",
                   "observed": dk, "held": d2},
            "D3": {"text": "the change feed ends with 0 wrong rows",
                   "observed": designs["change_feed"]["last"]["wrong"],
                   "held": designs["change_feed"]["last"]["wrong"] == 0}},
    }
    if ok:
        path = os.path.join(out, "second_recording.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, "source": {k: v for k, v in src.items() if k != "deletions"},
                      "last_wrong": {n: designs[n]["last"]["wrong"] for n in MAIN}, "deleted_kept": dk}))
    print("VERDICT:", "PASS" if ok else "FAIL control mismatch, nothing written")


if __name__ == "__main__":
    main()
