"""The reconciliation checks, frozen before any fault was run. Each returns its measurements and whether it fires.

totals            count and sums per source, source side from the raw file with the rule document's units
totals_by_status  count and principal per source and status, source statuses grouped through the rule document's map
target_rules      19 rules on the converted table, from the target schema (failure counts per rule)
code_census       every value of every coded source field must be a key of its code map
record_compare    the SQL result against the independent Python re-implementation, record by record
sample_review     a sample of source records traced to the target by a reviewer who knows the correct rules
"""
import math
import random

TOL = 1.0
AS_OF = "2026-09-30"
COMMERCIAL = ("undisbursed", "active", "paid_in_full", "charged_off", "cancelled", "closed_other")
RESIDENTIAL = ("originated", "approved_not_accepted", "denied", "withdrawn", "incomplete", "purchased")
COMPARE = ["source_system", "source_row", "segment", "record_kind", "status", "product", "origination_date",
           "fiscal_year", "origination_year", "principal_usd", "guaranteed_usd", "third_party_usd", "rate_type",
           "term_months", "is_revolver", "paid_in_full_date", "chargeoff_date", "chargeoff_usd", "lender_key",
           "lender_name", "lender_fdic_cert", "borrower_state", "borrower_zip5", "applicant_income_usd",
           "sold_secondary", "exact_duplicate"]


def _q(con, sql):
    return con.execute(sql).fetchall()


def source_totals(con, rules):
    u = rules["units"]
    out = {}
    r = _q(con, f"""SELECT count(*), sum(CAST(GrossApproval AS DOUBLE)) * {u['7A.GrossApproval']},
        coalesce(sum(CAST(SBAGuaranteedApproval AS DOUBLE)), 0) * {u['7A.SBAGuaranteedApproval']},
        coalesce(sum(CAST(GrossChargeOffAmount AS DOUBLE)), 0) * {u['7A.GrossChargeOffAmount']} FROM raw_7a""")[0]
    out["7A"] = r
    r = _q(con, f"""SELECT count(*), sum(CAST(GrossApproval AS DOUBLE)) * {u['504.GrossApproval']}, 0,
        coalesce(sum(CAST(GrossChargeOffAmount AS DOUBLE)), 0) * {u['504.GrossChargeOffAmount']} FROM raw_504""")[0]
    out["504"] = r
    r = _q(con, f"""SELECT count(*), sum(CAST(loan_amount_000s AS DOUBLE)) * {u['HMDA.loan_amount_000s']}, 0, 0
        FROM raw_hm""")[0]
    out["HMDA"] = r
    return {k: [int(v[0])] + [float(x or 0) for x in v[1:]] for k, v in out.items()}


def target_totals(con, table="loan"):
    rows = _q(con, f"""SELECT source_system, count(*), coalesce(sum(principal_usd), 0), coalesce(sum(guaranteed_usd), 0),
        coalesce(sum(chargeoff_usd), 0) FROM {table} GROUP BY 1""")
    return {r[0]: [int(r[1])] + [float(x) for x in r[2:]] for r in rows}


def totals(con, rules, table="loan"):
    s, t = source_totals(con, rules), target_totals(con, table)
    names = ["count", "principal", "guaranteed", "chargeoff"]
    diffs = {}
    for src in ("7A", "504", "HMDA"):
        tv = t.get(src, [0, 0.0, 0.0, 0.0])
        for i, n in enumerate(names):
            d = tv[i] - s[src][i]
            if (i == 0 and d != 0) or (i > 0 and abs(d) > TOL):
                diffs[f"{src}.{n}"] = round(d, 2)
    return {"fires": bool(diffs), "diffs": diffs, "source": s, "target": t}


def totals_by_status(con, rules, table="loan"):
    """Source statuses are grouped through map_status, which convert() loaded from the same rule document."""
    u = rules["units"]
    src = _q(con, f"""
        SELECT '7A', m.status, count(*), sum(CAST(r.GrossApproval AS DOUBLE)) * {u['7A.GrossApproval']}
          FROM raw_7a r LEFT JOIN map_status m ON m.source = '7A' AND m.code = r.LoanStatus GROUP BY 1, 2
        UNION ALL
        SELECT '504', m.status, count(*), sum(CAST(r.GrossApproval AS DOUBLE)) * {u['504.GrossApproval']}
          FROM raw_504 r LEFT JOIN map_status m ON m.source = '504' AND m.code = r.LoanStatus GROUP BY 1, 2
        UNION ALL
        SELECT 'HMDA', m.status, count(*), sum(CAST(r.loan_amount_000s AS DOUBLE)) * {u['HMDA.loan_amount_000s']}
          FROM raw_hm r LEFT JOIN map_status m ON m.source = 'HMDA' AND m.code = r.action_taken GROUP BY 1, 2""")
    tgt = _q(con, f"SELECT source_system, status, count(*), coalesce(sum(principal_usd), 0) FROM {table} GROUP BY 1, 2")
    s = {(a, b): (int(c), float(d or 0)) for a, b, c, d in src}
    t = {(a, b): (int(c), float(d or 0)) for a, b, c, d in tgt}
    diffs = {}
    for k in set(s) | set(t):
        sv, tv = s.get(k, (0, 0.0)), t.get(k, (0, 0.0))
        if sv[0] != tv[0] or abs(sv[1] - tv[1]) > TOL:
            diffs[f"{k[0]}.{k[1]}"] = {"count": tv[0] - sv[0], "principal": round(tv[1] - sv[1], 2)}
    return {"fires": bool(diffs), "diffs": diffs}


RULE_SQL = {
    "R01": "SELECT (count(*) - count(DISTINCT loan_id)) + count(*) FILTER (WHERE loan_id IS NULL) FROM {t}",
    "R02": "SELECT count(*) FROM {t} WHERE status IS NULL",
    "R03": "SELECT count(*) FROM {t} WHERE status IS NOT NULL AND NOT ((segment = 'commercial' AND status IN "
           + str(COMMERCIAL) + ") OR (segment = 'residential' AND status IN " + str(RESIDENTIAL) + "))",
    "R04": "SELECT count(*) FROM {t} WHERE record_kind IS NULL OR record_kind NOT IN ('loan', 'application')",
    "R05": "SELECT count(*) FROM {t} WHERE principal_usd IS NULL OR principal_usd < 1000 OR principal_usd > 50000000",
    "R06": "SELECT count(*) FROM {t} WHERE guaranteed_usd > principal_usd",
    "R07": "SELECT count(*) FROM {t} WHERE rate_decimal < 0 OR rate_decimal > 0.25",
    "R08": "SELECT count(*) FROM {t} WHERE term_months < 1 OR term_months > 480",
    "R09": "SELECT count(*) FROM {t} WHERE chargeoff_usd > 0 AND status IS DISTINCT FROM 'charged_off'",
    "R10": "SELECT count(*) FROM {t} WHERE status = 'charged_off' AND chargeoff_date IS NULL",
    "R11": "SELECT count(*) FROM {t} WHERE chargeoff_date IS NOT NULL AND status IS DISTINCT FROM 'charged_off'",
    "R12": "SELECT count(*) FROM {t} WHERE status = 'paid_in_full' AND paid_in_full_date IS NULL",
    "R13": "SELECT count(*) FROM {t} WHERE paid_in_full_date < origination_date OR chargeoff_date < origination_date",
    "R14": "SELECT count(*) FROM {t} WHERE origination_date < DATE '1990-10-01' OR origination_date > DATE '" + AS_OF + "'",
    "R15": "SELECT count(*) FROM {t} WHERE fiscal_year IS NOT NULL AND origination_date IS NOT NULL AND fiscal_year <> "
           "year(origination_date) + CASE WHEN month(origination_date) >= 10 THEN 1 ELSE 0 END",
    "R16": "SELECT count(*) FROM {t} WHERE applicant_income_usd < 1000 OR applicant_income_usd > 100000000",
    "R17": "SELECT count(*) FROM {t} WHERE source_system = '7A' AND is_revolver IS NULL",
    "R18": "SELECT count(*) FROM {t} WHERE lender_name IS NULL",
    "R19": "SELECT count(*) FROM {t} WHERE chargeoff_usd > principal_usd",
}


def target_rules(con, table="loan", baseline=None):
    counts = {k: int(_q(con, sql.format(t=table))[0][0]) for k, sql in RULE_SQL.items()}
    if baseline is None:
        return {"counts": counts}
    moved = {k: counts[k] - baseline[k] for k in counts if counts[k] != baseline[k]}
    return {"fires": bool(moved), "counts": counts, "moved": moved}


def code_census(con, rules):
    raw = {"7A": "raw_7a", "504": "raw_504", "HMDA": "raw_hm"}
    unmapped = {}
    for src, field, mapname in rules["coded_fields"]:
        keys = set(rules[mapname].get(src, {}))
        vals = _q(con, f'SELECT "{field}", count(*) FROM {raw[src]} WHERE "{field}" IS NOT NULL GROUP BY 1')
        miss = {v: int(n) for v, n in vals if v not in keys}
        if miss:
            unmapped[f"{src}.{field}.{mapname}"] = miss
    return {"fires": bool(unmapped), "unmapped": unmapped}


def _diff_expr(col):
    if col == "rate_decimal":
        return "NOT (a.rate_decimal IS NULL AND b.rate_decimal IS NULL) AND (a.rate_decimal IS NULL OR " \
               "b.rate_decimal IS NULL OR abs(a.rate_decimal - b.rate_decimal) > 1e-9)"
    return f"a.{col} IS DISTINCT FROM b.{col}"


def compare_tables(con, a, b):
    """Record-by-record difference between table a (as converted) and b (as expected), keyed on loan_id.

    Returns counts, and leaves the affected loan_ids (missing, extra, repeated or different) in table _affected."""
    cols = COMPARE + ["rate_decimal"]
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _ac AS SELECT loan_id, count(*) AS n FROM {a} GROUP BY 1""")
    diff_cols = ", ".join(f"count(*) FILTER (WHERE {_diff_expr(c)}) AS d_{c}" for c in cols)
    any_diff = " OR ".join(f"({_diff_expr(c)})" for c in cols)
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _diff AS
        SELECT a.loan_id, ({any_diff}) AS differs FROM {a} a JOIN {b} b USING (loan_id)""")
    per_field = con.execute(f"SELECT {diff_cols} FROM {a} a JOIN {b} b USING (loan_id)").fetchone()
    missing = _q(con, f"SELECT count(*) FROM {b} b WHERE b.loan_id NOT IN (SELECT loan_id FROM _ac)")[0][0]
    extra = _q(con, f"SELECT count(*) FROM _ac WHERE loan_id NOT IN (SELECT loan_id FROM {b})")[0][0]
    repeated = _q(con, "SELECT count(*), coalesce(sum(n - 1), 0) FROM _ac WHERE n > 1")[0]
    con.execute(f"""CREATE OR REPLACE TEMP TABLE _affected AS
        SELECT loan_id FROM {b} WHERE loan_id NOT IN (SELECT loan_id FROM _ac)
        UNION SELECT loan_id FROM _ac WHERE n > 1 OR loan_id NOT IN (SELECT loan_id FROM {b})
        UNION SELECT loan_id FROM _diff WHERE differs""")
    differing = _q(con, "SELECT count(DISTINCT loan_id) FROM _diff WHERE differs")[0][0]
    fields = {c: int(v) for c, v in zip(cols, per_field) if v}
    n_aff = _q(con, "SELECT count(*) FROM _affected")[0][0]
    return {"missing": int(missing), "extra_ids": int(extra), "repeated_ids": int(repeated[0]),
            "extra_copies": int(repeated[1]), "records_differ": int(differing), "fields": fields,
            "affected": int(n_aff)}


def record_compare(con, table="loan", ref="ref"):
    r = compare_tables(con, table, ref)
    r["fires"] = bool(r["missing"] or r["extra_ids"] or r["repeated_ids"] or r["records_differ"])
    return r


def _log_comb(n, k):
    return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)


def sample_review(con, affected_by_source, n_per_source, seed):
    """affected_by_source: {source: (N rows, set of affected source rows)}. Exact probability that a simple random
    sample of n per source draws at least one affected row, and one seeded draw."""
    log_none = 0.0
    hit = False
    drawn = {}
    for src in ("7A", "504", "HMDA"):
        n_rows, aff = affected_by_source[src]
        k = len(aff)
        n = min(n_per_source, n_rows)
        if k > n_rows - n:
            log_none = -math.inf
        elif k:
            log_none += _log_comb(n_rows - k, n) - _log_comb(n_rows, n)
        rng = random.Random(f"{seed}-{src}")
        pick = rng.sample(range(1, n_rows + 1), n)
        h = sum(1 for p in pick if p in aff)
        drawn[src] = h
        hit = hit or h > 0
    p = 1.0 - (0.0 if log_none == -math.inf else math.exp(log_none))
    return {"p_catch": p, "seeded_draw_fires": hit, "affected_drawn": drawn}
