"""Second part: link lenders to their FDIC identity, measure match rates and the fields that conflict per source pair,
and apply the declared source-wins rule (protocol-r1.json, lenders).

Usage: python3 -B tools/lenders.py <work dir>   (after run_study.py prepare)
"""
import json
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import lib  # noqa: E402

DROP = {"THE", "INC", "CORP", "CORPORATION", "CO", "COMPANY"}


def norm(name):
    if not name:
        return ""
    s = name.upper().replace("&", " AND ")
    s = re.sub(r"[^A-Z0-9 ]", " ", s)
    s = re.sub(r"\bNATIONAL ASSOCIATION\b", " ", s)
    s = re.sub(r"\bN A\b", " ", s)
    words = [w for w in s.split() if w not in DROP and w != "NA"]
    return " ".join(words)


def up(s):
    return " ".join((s or "").upper().split())


def main(work):
    con = lib.connect(Path(work) / "study.duckdb", read_only=True)
    sba = con.execute("""SELECT LocationID, BankName, BankCity, BankState, left(BankZip, 5), TRY_CAST(BankFDICNumber AS INTEGER),
                                count(*) AS loans
                         FROM raw_7a WHERE BankFDICNumber IS NOT NULL GROUP BY ALL""").fetchall()
    by_loc = defaultdict(list)
    for loc, name, city, st, z, cert, n in sba:
        by_loc[loc].append((n, name, city, st, z, cert))
    locs = {}
    variants = 0
    for loc, rows in by_loc.items():
        rows.sort(reverse=True)
        variants += len(rows) > 1
        n_total = sum(r[0] for r in rows)
        _, name, city, st, z, cert = rows[0]
        locs[loc] = {"name": name, "city": city, "state": st, "zip5": z, "cert": cert, "loans": n_total}
    fdic = {r[0]: {"name": r[1], "city": r[2], "state": r[3], "zip5": (r[4] or "")[:5], "active": r[5], "rssd": r[6]}
            for r in con.execute("SELECT cert, name, city, stalp, zip, active, fed_rssd FROM fdic").fetchall()}
    idx = {k: defaultdict(set) for k in ("name", "name_state", "name_city_state")}
    for cert, f in fdic.items():
        n = norm(f["name"])
        idx["name"][n].add(cert)
        idx["name_state"][(n, f["state"])].add(cert)
        idx["name_city_state"][(n, up(f["city"]), f["state"])].add(cert)

    matchers = {}
    for m in ("name", "name_state", "name_city_state"):
        c = Counter()
        loans = Counter()
        for loc, s in locs.items():
            n = norm(s["name"])
            key = {"name": n, "name_state": (n, s["state"]), "name_city_state": (n, up(s["city"]), s["state"])}[m]
            cand = idx[m].get(key, set())
            if len(cand) == 1:
                verdict = "right" if next(iter(cand)) == s["cert"] else "wrong"
            else:
                verdict = "none" if not cand else "ambiguous"
            c[verdict] += 1
            loans[verdict] += s["loans"]
        linked = c["right"] + c["wrong"]
        matchers[m] = {"locations": len(locs), **dict(c), "recall": c["right"] / len(locs),
                       "precision": (c["right"] / linked) if linked else None, "loans": dict(loans)}

    # Added after the results: the same name-and-state key, with candidates limited to institutions active today.
    act = defaultdict(set)
    for cert, f in fdic.items():
        if f["active"]:
            act[(norm(f["name"]), f["state"])].add(cert)
    c = Counter()
    for loc, s in locs.items():
        cand = act.get((norm(s["name"]), s["state"]), set())
        c["right" if cand == {s["cert"]} else "wrong" if len(cand) == 1 else "none" if not cand else "ambiguous"] += 1
    linked = c["right"] + c["wrong"]
    matchers["name_state_active_after_results"] = {"locations": len(locs), **dict(c), "recall": c["right"] / len(locs),
                                                   "precision": (c["right"] / linked) if linked else None}

    conflicts = Counter()
    decided = Counter()
    examples = defaultdict(int)
    for loc, s in locs.items():
        f = fdic.get(s["cert"])
        if f is None:
            conflicts["cert_not_in_fdic"] += 1
            continue
        if norm(s["name"]) != norm(f["name"]):
            conflicts["name"] += 1
            decided["name: FDIC"] += 1
        if up(s["name"]) != up(f["name"]):
            conflicts["name_as_written"] += 1
        if up(s["city"]) != up(f["city"]):
            conflicts["city"] += 1
            decided["city: FDIC"] += 1
        if s["state"] != f["state"]:
            conflicts["state"] += 1
            decided["state: FDIC"] += 1
        if (s["zip5"] or "") != (f["zip5"] or ""):
            conflicts["zip5"] += 1
            decided["zip5: FDIC"] += 1
        if not f["active"]:
            conflicts["fdic_inactive"] += 1
            examples["inactive_loans"] += s["loans"]
    true_pairs = len(locs) - conflicts["cert_not_in_fdic"]
    certs_per_name = Counter(norm(s["name"]) for s in locs.values())

    hm = con.execute("""SELECT DISTINCT h.agency_code, h.respondent_id, p."Respondent Name (Panel)", p."Respondent City (Panel)",
                               p."Respondent State (Panel)", p."Respondent RSSD ID"
                        FROM raw_hm h JOIN raw_panel p ON p."Respondent ID" = h.respondent_id AND p."Agency Code" = h.agency_code""").fetchall()
    by_rssd = {}
    for cert, f in fdic.items():
        if f["rssd"] and f["rssd"] != "0":
            by_rssd.setdefault(f["rssd"].lstrip("0"), []).append(cert)
    hc = Counter()
    for agency, rid, name, city, st, rssd in hm:
        hc["lenders"] += 1
        key = (rssd or "").lstrip("0")
        certs = by_rssd.get(key) if key else None
        if not certs:
            hc["no_fdic_record"] += 1
            continue
        f = fdic[certs[0]]
        hc["linked"] += 1
        hc["name"] += norm(name) != norm(f["name"])
        hc["city"] += up(city) != up(f["city"])
        hc["state"] += (st or "") != (f["state"] or "")
        hc["fdic_inactive"] += not f["active"]
    out = {"sba_locations_with_cert": len(locs), "sba_locations_with_variant_rows": variants, "true_pairs": true_pairs,
           "matchers": matchers, "conflicts_sba_fdic": dict(conflicts),
           "conflict_shares_sba_fdic": {k: v / true_pairs for k, v in conflicts.items() if k != "cert_not_in_fdic"},
           "loans_at_inactive_certs": examples["inactive_loans"],
           "source_wins_decisions": dict(decided),
           "names_shared_by_several_locations": sum(1 for v in certs_per_name.values() if v > 1),
           "hmda_fdic": dict(hc), "rule": lib.PROTOCOL["lenders"]["source_wins"]}
    (lib.ROOT / "results" / "lenders-r1.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({k: out[k] for k in ("sba_locations_with_cert", "true_pairs", "conflicts_sba_fdic", "hmda_fdic",
                                          "loans_at_inactive_certs")}, indent=0))
    for m, v in matchers.items():
        print(m, {k: (round(x, 4) if isinstance(x, float) else x) for k, x in v.items() if k != "loans"})


if __name__ == "__main__":
    main(sys.argv[1])
