"""Tests: the row contract, each design on a small source that revises, re-keys, deletes and publishes late, the
scoring, the retries, the outage backfill, the owners, the drift loaders, and the published results.

Run: python3 -B tests/test_pipeline.py   (needs dagster and duckdb; see README.md)
"""
import gzip
import json
import os
import subprocess
import sys
import tempfile
import unittest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tools"))
sys.path.insert(0, os.path.join(ROOT, "dag"))
os.environ["PIPELINE_RETRY_DELAY"] = "0"

from contract import check, split  # noqa: E402
from replay import iso_ms, planted_failure  # noqa: E402
from score import Truth, compare  # noqa: E402

M = 60 * 1000
T0, T1, T2 = iso_ms("2026-11-11T18:50:00Z"), iso_ms("2026-11-11T19:10:00Z"), iso_ms("2026-11-11T20:05:00Z")


def ev(i, time, updated, mag=2.0, status="reviewed", ids=None):
    return {"id": i, "ids": ids or f",{i},", "status": status, "mag": mag, "magType": "ml", "time": time,
            "updated": updated, "type": "earthquake", "net": "ak", "lon": -150.0, "lat": 61.0, "depth": 10.0,
            "nbytes": 700}


A = ev("A", T0 - 180 * M, T0 - 120 * M)
B = ev("B", T0 - 120 * M, T0 - 60 * M)
C = ev("C", T0 - 90 * M, T0 - 80 * M)
Q = dict(ev("Q", None, T0 - 70 * M), status=None, mag=None)  # a record with no origin time, as the real feed has
X = ev("X", T0 - 200 * M, T0 - 150 * M, status="deleted")
B1 = dict(B, mag=2.5, updated=T1 - 5 * M)  # revised magnitude
C1 = dict(C, status="deleted", updated=T1 - 4 * M)  # deleted
D = ev("D", A["time"], T1 - 3 * M, ids=",A,D,")  # A re-keyed: the same event under a new preferred id
F = ev("F", T1 - 50 * M, T1 - 2 * M)
E = ev("E", T2 - 40 * M, T1 - 3 * M)  # published late: its updated time is before the watermark already read
TICKS = [(T0, [A, B, C, Q, X]), (T1, [B1, C1, D, F, Q, X]), (T2, [B1, C1, D, F, E, Q, X])]


def write_ticks(folder):
    for n, (t, rows) in enumerate(TICKS):
        meta = {"tick": n, "fetched_utc": __import__("datetime").datetime.fromtimestamp(t / 1000, __import__("datetime").timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
                "attempts": 1, "response_bytes": 1000, "rows": len(rows)}
        with gzip.open(os.path.join(folder, f"tick-{n:04d}.jsonl.gz"), "wt", encoding="utf-8") as f:
            f.write(json.dumps(meta) + "\n")
            for r in rows:
                f.write(json.dumps(r) + "\n")


def last(rows, arm, design):
    rs = [r for r in rows if r["arm"] == arm and r["design"] == design]
    return max(rs, key=lambda r: r["tick"])


class Contract(unittest.TestCase):
    def test_rejects_missing_time_and_casts_integer_magnitude(self):
        self.assertEqual(check(Q), "origin time missing or not an integer")
        good, bad, _ = split([dict(A, mag=3)])
        self.assertIsInstance(good[0]["mag"], float)
        self.assertEqual(bad, [])

    def test_unknown_keys_are_audited_not_fatal(self):
        good, bad, extra = split([dict(A, schema={"extra": ["new_field"], "missing": []})])
        self.assertEqual((len(good), len(bad), extra), (1, 0, [("A", "new_field")]))


class Scoring(unittest.TestCase):
    def test_classes(self):
        truth = Truth([B1, C1, D, F, E, Q, X])
        table = [dict(A), dict(B), dict(C), dict(D), dict(F), dict(F)]
        errs, _ = compare([{k: v for k, v in r.items() if k != "nbytes"} for r in table], truth)
        self.assertEqual(errs["old_key"], 1)  # A, while D is also present: a duplicate
        self.assertEqual(errs["stale"], 1)  # B with the old magnitude
        self.assertEqual(errs["deleted_kept"], 1)  # C
        self.assertEqual(errs["missing"], 1)  # E
        self.assertEqual(errs["repeat"], 1)  # F twice
        self.assertEqual(errs["duplicates"], 2)
        self.assertEqual(errs["wrong"], 5)


class Faults(unittest.TestCase):
    def test_planted_failures_are_seeded_and_rare(self):
        grid = [planted_failure("change_feed", t, 1) for t in range(1, 2001)]
        self.assertEqual(grid, [planted_failure("change_feed", t, 1) for t in range(1, 2001)])
        self.assertTrue(150 < sum(grid) < 250)  # about 10% of first attempts
        four = sum(planted_failure(d, t, 4) for d in ("a", "b", "c", "d") for t in range(1, 2001))
        self.assertTrue(four < 30)  # about 0.27% of runs fail all four attempts

    def test_retry_policy_recovers_three_failures_and_gives_up_on_four(self):
        import dagster as dg
        import definitions as D
        from replay import ReplayView

        class Src:
            def __init__(self, k):
                self.k = k
                self.current = ReplayView({"tick": 1, "fetched_utc": "2026-11-11T19:10:00Z"}, TICKS[1][1])

            def view(self, key):
                return self.current

            def is_initial(self, key, design):
                return True

            def interval(self, key):
                return None

            def count(self, view):
                return 4

            def fails(self, design, key, attempt):
                return attempt <= self.k

        asset = [a for a in D.ASSETS if a.key.path[-1] == "events_full_reload"]
        with tempfile.TemporaryDirectory() as d:
            inst = dg.DagsterInstance.ephemeral()
            inst.add_dynamic_partitions("ticks", ["1"])
            ok = dg.materialize(asset, instance=inst, partition_key="1", raise_on_error=False,
                                resources={"source": Src(3), "warehouse": D.Warehouse(d)})
            self.assertTrue(ok.success)
            md = ok.get_asset_materialization_events()[0].event_specific_data.materialization.metadata
            self.assertEqual(md["attempt"].value, 4)
            bad = dg.materialize(asset, instance=inst, partition_key="1", raise_on_error=False,
                                 resources={"source": Src(4), "warehouse": D.Warehouse(os.path.join(d, "b"))})
            self.assertFalse(bad.success)

    def test_a_code_error_is_not_retried_and_a_source_outage_is(self):
        import dagster as dg
        import definitions as D
        from source import SourceUnavailable

        class Src:
            def __init__(self, exc):
                self.exc, self.calls = exc, 0

            def view(self, key):
                self.calls += 1
                raise self.exc

            def fails(self, design, key, attempt):
                return False

        asset = [a for a in D.ASSETS if a.key.path[-1] == "events_full_reload"]
        for exc, calls in ((RuntimeError("a bug"), 1), (ValueError("bad data"), 1), (SourceUnavailable("503"), 4)):
            with tempfile.TemporaryDirectory() as d:
                inst = dg.DagsterInstance.ephemeral()
                inst.add_dynamic_partitions("ticks", ["1"])
                src = Src(exc)
                res = dg.materialize(asset, instance=inst, partition_key="1", raise_on_error=False,
                                     resources={"source": src, "warehouse": D.Warehouse(d)})
                self.assertFalse(res.success)
                self.assertEqual(src.calls, calls, type(exc).__name__)


class EndToEnd(unittest.TestCase):
    """The replay driver on the three-tick source, both arms, faults off."""

    @classmethod
    def setUpClass(cls):
        cls.tmp = tempfile.TemporaryDirectory()
        src = os.path.join(cls.tmp.name, "ticks")
        os.makedirs(src)
        write_ticks(src)
        env = dict(os.environ, PIPELINE_FAULTS="off")
        subprocess.run([sys.executable, "-B", os.path.join(ROOT, "tools", "run_study.py"), src,
                        os.path.join(cls.tmp.name, "out"), os.path.join(cls.tmp.name, "work")],
                       check=True, env=env, capture_output=True)
        with open(os.path.join(cls.tmp.name, "out", "ticks.jsonl"), encoding="utf-8") as f:
            cls.rows = [json.loads(line) for line in f]

    @classmethod
    def tearDownClass(cls):
        cls.tmp.cleanup()

    def wrong(self, arm, design):
        return last(self.rows, arm, design)["errors"]

    def test_full_reload_is_right(self):
        self.assertEqual(self.wrong("no_outage", "full_reload")["wrong"], 0)

    def test_incremental_keeps_the_deleted_and_the_old_key_and_misses_the_late_event(self):
        e = self.wrong("no_outage", "incremental_updated")
        self.assertEqual((e.get("old_key"), e.get("deleted_kept"), e.get("missing"), e["wrong"]), (1, 1, 1, 3))
        self.assertEqual(e["duplicates"], 1)

    def test_change_feed_is_right_and_lookback_zero_misses_the_late_event(self):
        self.assertEqual(self.wrong("no_outage", "change_feed")["wrong"], 0)
        self.assertEqual(self.wrong("no_outage", "change_feed_lookback_0")["missing"], 1)

    def test_time_partitions(self):
        e = self.wrong("no_outage", "time_partitions")
        self.assertEqual((e.get("old_key"), e.get("stale"), e.get("deleted_kept"), e["wrong"]), (1, 1, 1, 3))

    def test_quarantine_counts_in_neither_side(self):
        for r in self.rows:
            self.assertNotIn("Q", sum(r["example_ids"].values(), []))

    def test_outage_backfill(self):
        r = last(self.rows, "outage", "time_partitions")
        self.assertEqual(r["phase"], "backfill")
        self.assertEqual([p["key"] for p in r["backfill_partitions"]], ["1"])
        self.assertEqual(r["errors"]["wrong"], 3)
        self.assertEqual(self.wrong("outage", "incremental_updated")["wrong"], 2)  # the late event is read this time
        self.assertEqual(self.wrong("outage", "change_feed")["wrong"], 0)
        skipped = [x for x in self.rows if x["arm"] == "outage" and x["tick"] == 1]
        self.assertTrue(all(x["phase"] == "skipped" for x in skipped))


class Owners(unittest.TestCase):
    def test_every_check_and_table_has_an_owner(self):
        import definitions as D
        g = json.load(open(os.path.join(ROOT, "governance.json"), encoding="utf-8"))
        self.assertEqual(set(g["checks"]), set(D.CHECKS))
        for c in g["checks"].values():
            self.assertIn(c["owner"], g["roles"])
        for t in g["tables"].values():
            self.assertIn(t["owner"], g["roles"])
        self.assertEqual(g["schemas"]["quarantine"]["read"], ["data_platform", "feed_owner"])


class Drift(unittest.TestCase):
    def test_published_drift_counts(self):
        with tempfile.TemporaryDirectory() as d:
            out = os.path.join(d, "drift.json")
            subprocess.run([sys.executable, "-I", "-B", os.path.join(ROOT, "tools", "drift.py"),
                            os.path.join(ROOT, "data", "gharchive"), out], check=True, capture_output=True)
            got = json.load(open(out, encoding="utf-8"))
        pub = json.load(open(os.path.join(ROOT, "results", "drift.json"), encoding="utf-8"))
        self.assertEqual(got, pub)
        self.assertEqual(got["totals"]["lenient"]["silently_null"], 4000)
        self.assertEqual(got["totals"]["versioned"]["right"], 10000)


class Published(unittest.TestCase):
    def test_summary_rebuilds_from_the_tick_results(self):
        ticks = os.path.join(ROOT, "results", "ticks.jsonl.gz")
        if not os.path.exists(ticks):
            self.skipTest("no published run yet")
        with tempfile.TemporaryDirectory() as d:
            out = os.path.join(d, "summary.json")
            subprocess.run([sys.executable, "-I", "-B", os.path.join(ROOT, "tools", "summarize.py"),
                            os.path.join(ROOT, "results"), out], check=True, capture_output=True)
            got = json.load(open(out, encoding="utf-8"))
        self.assertEqual(got, json.load(open(os.path.join(ROOT, "results", "summary.json"), encoding="utf-8")))

    def test_replay_of_the_first_recorded_reads_matches_the_published_rows(self):
        """Replays the first three reads of the recorded log, with the seeded faults, and compares every row."""
        ticks = os.path.join(ROOT, "results", "ticks.jsonl.gz")
        if not os.path.exists(ticks):
            self.skipTest("no published run yet")
        n = 3
        with tempfile.TemporaryDirectory() as d:
            log = os.path.join(d, "first.jsonl.gz")
            with gzip.open(os.path.join(ROOT, "data", "source-log.jsonl.gz"), "rt", encoding="utf-8") as f, \
                    gzip.open(log, "wt", encoding="utf-8") as g:
                for _ in range(n):
                    g.write(f.readline())
            env = dict(os.environ)
            env.pop("PIPELINE_FAULTS", None)
            subprocess.run([sys.executable, "-B", os.path.join(ROOT, "tools", "run_study.py"), log,
                            os.path.join(d, "out"), os.path.join(d, "work")], check=True, env=env, capture_output=True)
            with open(os.path.join(d, "out", "ticks.jsonl"), encoding="utf-8") as f:
                got = [json.loads(line) for line in f]
        with gzip.open(ticks, "rt", encoding="utf-8") as f:
            pub = [r for r in map(json.loads, f) if r["tick"] < n]

        def key(r):
            return (r["arm"], r["design"], r["tick"])
        self.assertEqual(len(got), len(pub))
        self.assertEqual(sorted(got, key=key), sorted(pub, key=key))


if __name__ == "__main__":
    unittest.main(verbosity=1)
