"""Tests: the rule patches, the sample odds, the rounding rule, the record compare, the fault generator, the lender
name cleaning, and replays: the summary and the pages from the stored runs, and (with the raw files) every run itself.

Run from the study folder: python3 -B -m pytest -q tests
The run replays need the raw files: set LDC_RAW to the raw folder and LDC_REPLAY to an empty work folder. Without them
those tests are skipped. They run in order (prepare, then main, fresh and lenders) and each compares its output with
the published result file.
"""
import json
import math
import os
import random
import shutil
import subprocess
import sys
from decimal import Decimal
from pathlib import Path

import duckdb
import pytest

ROOT = Path(__file__).resolve().parent.parent
TOOLS = ROOT / "tools"
sys.path.insert(0, str(TOOLS))
import checks  # noqa: E402
import fresh_faults  # noqa: E402
import lenders  # noqa: E402
import lib  # noqa: E402
import reference  # noqa: E402

RAW = os.environ.get("LDC_RAW")
REPLAY = os.environ.get("LDC_REPLAY")
needs_data = pytest.mark.skipif(not (RAW and REPLAY), reason="set LDC_RAW and LDC_REPLAY to replay the runs")


def res(name, root=ROOT):
    return json.loads((root / "results" / name).read_text(encoding="utf-8"))


def same(x, y, path="", out=None):
    """Differences between two result trees. Floats may differ in the last digits: the source-side totals are sums of
    doubles over threads, so their order (and last bits) can change between runs. Every check's verdict uses a US$1
    tolerance, far above that."""
    out = [] if out is None else out
    if isinstance(x, dict) and isinstance(y, dict):
        for k in sorted(set(x) | set(y)):
            same(x.get(k), y.get(k), f"{path}/{k}", out)
    elif isinstance(x, list) and isinstance(y, list) and len(x) == len(y):
        for i, (u, v) in enumerate(zip(x, y)):
            same(u, v, f"{path}[{i}]", out)
    elif isinstance(x, float) and isinstance(y, float) and not isinstance(x, bool):
        if not math.isclose(x, y, rel_tol=1e-12, abs_tol=1e-6):
            out.append(path)
    elif x != y:
        out.append(path)
    return out


def copy_study(dst):
    """A copy of the study folder without its export, private notes and caches, so a replay writes only there."""
    if dst.exists():
        shutil.rmtree(dst)
    shutil.copytree(ROOT, dst, ignore=shutil.ignore_patterns("public-export", "_private", "__pycache__",
                                                             ".pytest_cache", "vendor"))
    return dst


def test_rule_document_fields_are_the_target_columns():
    assert [f["target"] for f in lib.RULES["fields"]] == lib.COLUMNS and len(lib.COLUMNS) == 28


def test_patch_rules_leaves_the_rule_document_alone():
    before = json.dumps(lib.RULES, sort_keys=True)
    out = lib.patch_rules(lib.RULES, {"status_map.7A.P I F": None, "status_map.7A.PIF": "paid_in_full",
                                      "units.HMDA.loan_amount_000s": 1, "revolver_map.7A": {"0": False, "1": True}})
    assert json.dumps(lib.RULES, sort_keys=True) == before
    assert "P I F" not in out["status_map"]["7A"] and out["status_map"]["7A"]["PIF"] == "paid_in_full"
    assert out["units"]["HMDA.loan_amount_000s"] == 1 and out["revolver_map"]["7A"] == {"0": False, "1": True}


def test_sample_odds_match_a_direct_count():
    rng = random.Random(3)
    for _ in range(30):
        aff = {}
        none = 1.0
        for src in ("7A", "504", "HMDA"):
            n_rows = rng.randint(60, 400)
            k = rng.randint(0, 12)
            rows = set(rng.sample(range(1, n_rows + 1), k))
            aff[src] = (n_rows, rows)
            none *= math.comb(n_rows - k, 60) / math.comb(n_rows, 60)
        got = checks.sample_review(None, aff, 60, 7)["p_catch"]
        assert abs(got - (1 - none)) < 1e-9


def test_rounding_is_half_away_from_zero_in_both_builds():
    assert reference.money("3749992.425", 1) == Decimal("3749992.43")
    assert reference.money("-0.125", 1) == Decimal("-0.13")
    assert reference.money("245", 1000) == Decimal("245000.00")
    sql = ("SELECT CAST(round(CAST(x AS DECIMAL(18, 4)) * CAST(1 AS DECIMAL(18, 4)), 2) AS DECIMAL(14, 2)) "
           "FROM (VALUES ('3749992.425'), ('-0.125')) t(x)")
    assert [str(v) for (v,) in duckdb.sql(sql).fetchall()] == ["3749992.43", "-0.13"]


def test_record_compare_counts_missing_extra_repeated_and_changed():
    con = duckdb.connect()
    cols = ", ".join(f"{c} VARCHAR" if c != "rate_decimal" else "rate_decimal DOUBLE" for c in lib.COLUMNS)
    for t in ("a", "b"):
        con.execute(f"CREATE TABLE {t} ({cols})")
    rows = {"x1": None, "x2": None, "x3": None, "x4": None}
    for lid in rows:
        con.execute(f"INSERT INTO b (loan_id, status, rate_decimal) VALUES ('{lid}', 'active', 0.05)")
    con.execute("INSERT INTO a (loan_id, status, rate_decimal) VALUES ('x1', 'active', 0.05), ('x2', 'closed', 0.05), "
                "('x3', 'active', 0.0500000000001), ('x3', 'active', 0.05), ('x9', 'active', 0.05)")
    r = checks.record_compare(con, "a", "b")
    assert (r["missing"], r["extra_ids"], r["repeated_ids"], r["records_differ"]) == (1, 1, 1, 1)
    assert sorted(v for (v,) in con.execute("SELECT loan_id FROM _affected").fetchall()) == ["x2", "x3", "x4", "x9"]
    assert r["fires"] and r["affected"] == 4


def test_fresh_generator_is_fixed_by_its_seed():
    spec = lib.PROTOCOL["fresh_faults"]
    codes = {"7A": [("LoanStatus", ["CHGOFF", "EXEMPT", "P I F"])], "504": [("LoanStatus", ["CHGOFF", "PIF"])],
             "HMDA": [("action_taken", ["1", "3", "6"])]}

    def names():
        rng = fresh_faults.rng_for(spec["seed"])
        return [fresh_faults.draw(rng, spec, lib.RULES, codes, i)["name"] for i in range(60)]
    first = names()
    assert first == names() and len(set(first)) > 30


def test_published_fresh_draws_follow_the_declared_layer_rule():
    fr = res("fresh-r1.json")
    assert fr["seed"] == lib.PROTOCOL["fresh_faults"]["seed"] and len(fr["faults"]) == lib.PROTOCOL["fresh_faults"]["n"]
    assert fr["draws"] == len(fr["faults"]) + len(fr["redraws"])
    for f in fr["faults"]:
        assert f["effect"]["affected"] > 0, f["id"]
        if f["family"] not in ("remap", "scale"):
            assert f["layer"] == "code", f["id"]


def test_main_faults_ran_in_the_declared_order():
    assert [f["id"] for f in res("main-r1.json")["faults"]] == [f["id"] for f in lib.PROTOCOL["main_faults"]]


def test_lender_names_are_cleaned_as_declared():
    assert lenders.norm("The First National Bank of Omaha, N.A.") == "FIRST NATIONAL BANK OF OMAHA"
    assert lenders.norm("Wells & Sons Co.") == "WELLS AND SONS"
    assert lenders.norm("Bank, National Association") == "BANK"


def test_summary_replays_from_the_stored_runs(tmp_path):
    dst = copy_study(tmp_path / "study")
    subprocess.run([sys.executable, "-I", "-B", str(dst / "tools" / "summarize.py")], check=True, capture_output=True)
    assert res("summary-r1.json", dst) == res("summary-r1.json")


def test_second_version_replays_and_leaves_the_first_alone(tmp_path):
    dst = copy_study(tmp_path / "study")
    first = {f: (dst / "results" / f).read_bytes() for f in ("main-r1.json", "fresh-r1.json", "summary-r1.json")}
    subprocess.run([sys.executable, "-I", "-B", str(dst / "tools" / "change2.py")], check=True, capture_output=True)
    assert res("change2-r2.json", dst) == res("change2-r2.json")
    assert all((dst / "results" / f).read_bytes() == b for f, b in first.items())
    rows = res("change2-r2.json")["rules_on_rises"]["fresh"]["rows"]
    # a rule rise is a subset of a rule move, and the quick checks with rises never exceed those with any move
    assert all(r["rules_any_move"] or not r["rules_rise"] for r in rows)
    assert all(r["quick_any_move"] or not r["quick_rise"] for r in rows)


def test_third_version_bounds_and_sizing_follow_from_the_stored_runs():
    import change3
    assert abs(change3.upper_one_sided(0, 29) - (1 - 0.05 ** (1 / 29))) < 1e-9
    assert change3.upper_one_sided(1, 15) < res("change2-r2.json")["sizing"]["chargeoff_miss"]["upper_95"]
    stored = res("change3-r3.json")
    for which, name in (("main", "main-r1.json"), ("fresh", "fresh-r1.json")):
        assert change3.part_b(res(name)["faults"]) == stored["quick_check_bounds"][which]
    sz = stored["test"]["sized_for_80pct"]
    assert change3.upper_one_sided(sz["max_misses"], sz["n"]) < 0.10 <= change3.upper_one_sided(sz["max_misses"] + 1, sz["n"])
    # the totals variant only adds catches, and only on faults in the rule document
    for which in ("main", "fresh"):
        for r in stored["totals_source_units"][which]["rows"]:
            assert r["totals_source_units"] >= r["totals_first"]
            assert r["layer"] == "rule" or r["totals_source_units"] == r["totals_first"]


def test_fourth_version_follows_from_the_stored_runs(tmp_path):
    dst = copy_study(tmp_path / "study")
    first = {f: (dst / "results" / f).read_bytes() for f in ("main-r1.json", "fresh-r1.json", "change3-r3.json")}
    subprocess.run([sys.executable, "-I", "-B", str(dst / "tools" / "change4.py")], check=True, capture_output=True)
    assert res("change4-r4.json", dst) == res("change4-r4.json")
    assert all((dst / "results" / f).read_bytes() == b for f, b in first.items())
    v4, v3 = res("change4-r4.json"), res("change3-r3.json")
    # the low end adds to the high end exactly the charge-off faults the rules alone caught
    rl = v4["reversal_low_end"]
    alone = set(v3["quick_check_bounds"]["fresh"]["rules_alone"])
    assert set(rl["missed_low"]) == set(rl["missed_high"]) | (alone & set(res("summary-r1.json")["reversal"]["fresh_chargeoff_faults"]))
    assert set(v4["code_past_quick"]["high"]) <= set(v4["code_past_quick"]["low"])
    # in code, totals fire exactly on the faults whose effect touches a count or a summed amount; never in rules
    for which in ("main", "fresh"):
        for r in v4["totals_by_kind"][which]["rows"]:
            assert r["totals"] == r["touches"]
            assert r["layer"] == "code" or not r["totals"]
    td = v4["test_draws"]
    assert td["mean_draws"] < td["draws_for_95pct"] and td["chargeoff_moving_needed"] == v3["test"]["sized_for_80pct"]["n"]


def test_pages_replay_from_the_results(tmp_path):
    dst = copy_study(tmp_path / "study")
    subprocess.run([sys.executable, "-I", "-B", str(dst / "site" / "render.py")], check=True, capture_output=True)
    for pg in ("index.html", "fresh.html", "results.html", "lenders.html", "method.html"):
        assert (dst / pg).read_bytes() == (ROOT / pg).read_bytes(), pg


# ---------- replays of the runs themselves, from the raw files ----------
def replay_dirs():
    base = Path(REPLAY)
    return base / "study", base / "work"


def run(step, *args):
    study, _ = replay_dirs()
    subprocess.run([sys.executable, "-B", str(study / "tools" / step), *args], check=True, capture_output=True)


@needs_data
def test_replay_1_prepare():
    study, work = replay_dirs()
    copy_study(study)
    for f in ("prepare-r1.json", "main-r1.json", "fresh-r1.json", "lenders-r1.json", "summary-r1.json"):
        (study / "results" / f).unlink()
    run("run_study.py", "prepare", RAW, str(work))
    assert same(res("prepare-r1.json", study), res("prepare-r1.json")) == []


@needs_data
def test_replay_2_main_set():
    study, work = replay_dirs()
    if not (study / "results" / "prepare-r1.json").exists():
        pytest.skip("run test_replay_1_prepare first")
    run("run_study.py", "main", RAW, str(work))
    assert same(res("main-r1.json", study), res("main-r1.json")) == []


@needs_data
def test_replay_3_fresh_set():
    study, work = replay_dirs()
    if not (study / "results" / "prepare-r1.json").exists():
        pytest.skip("run test_replay_1_prepare first")
    run("run_study.py", "fresh", RAW, str(work))
    assert same(res("fresh-r1.json", study), res("fresh-r1.json")) == []


@needs_data
def test_replay_4_lenders():
    study, work = replay_dirs()
    if not (work / "study.duckdb").exists():
        pytest.skip("run test_replay_1_prepare first")
    run("lenders.py", str(work))
    assert same(res("lenders-r1.json", study), res("lenders-r1.json")) == []


@needs_data
def test_replay_5_third_version():
    study, work = replay_dirs()
    if not (work / "study.duckdb").exists():
        pytest.skip("run test_replay_1_prepare first")
    if not (study / "results" / "fresh-r1.json").exists():
        pytest.skip("run test_replay_2 and test_replay_3 first")
    # the summary is rebuilt from the replayed runs, then the third version from it and the work database
    subprocess.run([sys.executable, "-I", "-B", str(study / "tools" / "summarize.py")], check=True, capture_output=True)
    assert same(res("summary-r1.json", study), res("summary-r1.json")) == []
    run("change3.py", str(work))
    assert same(res("change3-r3.json", study), res("change3-r3.json")) == []
    run("change4.py")
    assert same(res("change4-r4.json", study), res("change4-r4.json")) == []
