"""Ecological inference of 1st -> 2nd round vote transfers (Brazil 2026, President).

Each unit (municipality now; municipality x zone once TSE publishes it) gives the share of
its electorate in each round-1 category x_i and each round-2 category y_i. Within a group of
units we estimate a row-stochastic transfer matrix B (P[round-2 choice | round-1 choice])
with y_i ~= x_i B:

  1. constrained weighted least squares per group (weights = electorate, every row of B on
     the probability simplex), solved by batched FISTA with simplex projection. Candidate
     groupings: one national B, per region, per state, per state x tercile of Lula's
     round-1 share, per municipality (section units only in effect). Units in a group of fewer than MIN_UNITS units use the coarser level's
     matrix, fitted on all of that level's units;
  2. the grouping with the lowest split-half out-of-sample error is the main estimate;
  3. unit-level refinement: seed each unit's table with diag(X_i) B_group and rake it (IPF)
     to that unit's round-1 and round-2 totals (round 2 rescaled to round 1's electorate).
     The sums match those margins by construction, whatever B is: bookkeeping, not evidence;
  4. bootstrap over units within state for a resampling spread.

The spread holds the grouping, the seed floor and the weights fixed and does not cover
ecological-inference bias (the dominant risk).

Usage: python3 -I transfer_model.py [input.csv] [unit-label]
"""
import csv
import json
import os
import sys

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "..", "data")
IN = sys.argv[1] if len(sys.argv) > 1 else os.path.join(DATA, "president_by_municipality.csv")
UNIT = sys.argv[2] if len(sys.argv) > 2 else "municipality"

R1 = ["Lula", "Flávio", "Augusto Cury", "Renan Santos", "Caiado", "Others", "Blank/Null", "Abstention"]
R2 = ["Lula", "Flávio", "Blank/Null", "Abstention"]
R1_CAND = {"Lula": ["13"], "Flávio": ["22"], "Augusto Cury": ["70"], "Renan Santos": ["14"],
           "Caiado": ["55"], "Others": ["30", "80", "16", "27", "21", "35", "29"]}
R2_CAND = {"Lula": ["13"], "Flávio": ["22"]}
REGION = {**{u: "North" for u in "AC AM AP PA RO RR TO".split()},
          **{u: "Northeast" for u in "AL BA CE MA PB PE PI RN SE".split()},
          **{u: "Center-West" for u in "DF GO MS MT".split()},
          **{u: "Southeast" for u in "ES MG RJ SP".split()},
          **{u: "South" for u in "PR RS SC".split()}, "ZZ": "Abroad"}
MIN_UNITS = 40
SEED_FLOOR = 0.01  # share of each seed row spread uniformly, so IPF can route any flow a unit needs
N_BOOT = 200
N_SPLITS = 20
rng = np.random.default_rng(20261025)


def load(path):
    rows = list(csv.DictReader(open(path, encoding="utf-8")))
    X = np.zeros((len(rows), len(R1)))
    Y = np.zeros((len(rows), len(R2)))
    for i, r in enumerate(rows):
        g = lambda k: int(r.get(k) or 0)
        for j, cat in enumerate(R1[:6]):
            X[i, j] = sum(g(f"r1_c{n}") for n in R1_CAND[cat])
        X[i, 6] = g("r1_blank") + g("r1_null") + g("r1_annulled")
        X[i, 7] = g("r1_electorate") - g("r1_turnout")
        for j, cat in enumerate(R2[:2]):
            Y[i, j] = sum(g(f"r2_c{n}") for n in R2_CAND[cat])
        Y[i, 2] = g("r2_blank") + g("r2_null") + g("r2_annulled")
        Y[i, 3] = g("r2_electorate") - g("r2_turnout")
    # in-transit voting moves a few hundred electors between rounds: put round 2 on round 1's electorate
    Y *= (X.sum(1) / Y.sum(1))[:, None]
    return rows, X, Y


def groupings(rows, X):
    """Candidate groupings, coarse to fine: grouping -> (labels, members).

    labels[i] names the matrix unit i uses; members[label] is the mask of units that matrix is fitted on.
    A unit in a group of under MIN_UNITS units uses its parent group's matrix, fitted on the whole parent
    (DF uses the Center-West matrix, AC/AP/RR the North one). Labels are object arrays: a fixed-width
    string array would truncate a region name assigned into a two-letter state array."""
    states = np.array([r["uf"] for r in rows], dtype=object)
    regions = np.array([REGION[s] for s in states], dtype=object)
    lula = X[:, 0] / X.sum(1)
    terc = np.empty(len(rows), dtype=object)
    for s in np.unique(states):
        m = states == s
        cuts = np.quantile(lula[m], [1 / 3, 2 / 3]) if m.sum() >= 3 * MIN_UNITS else [np.inf, np.inf]
        terc[m] = [f"{s}:t{int(v > cuts[0]) + int(v > cuts[1])}" for v in lula[m]]
    # tse_code is the municipality code, or "<municipality>-<zone>-<section>" for section units
    muni = np.array([f"{r['uf']}:m{r['tse_code'].split('-')[0]}" for r in rows], dtype=object)
    levels = [np.array(["BR"] * len(rows), dtype=object), regions, states, terc, muni]  # labels unique across levels

    def fold(fine, coarse):
        out = fine.copy()
        for g in np.unique(fine):
            m = fine == g
            if m.sum() < MIN_UNITS:
                out[m] = coarse[m]
        return out

    state = fold(states, regions)
    out = {}
    for k, labels in {"national": levels[0], "region": regions, "state": state,
                      "state x Lula-tercile": fold(terc, state), "municipality": fold(muni, state)}.items():
        members = {g: next(lv == g for lv in levels if (lv == g).any()) for g in np.unique(labels)}
        small = {g: int(m.sum()) for g, m in members.items() if m.sum() < MIN_UNITS}
        assert not small, f"{k}: groups fitted on under {MIN_UNITS} units: {small}"
        out[k] = (labels, members)
    return out


def project_simplex(V):
    """Euclidean projection of each row of V onto the probability simplex."""
    k = V.shape[-1]
    flat = V.reshape(-1, k)
    U = -np.sort(-flat, axis=1)
    css = np.cumsum(U, axis=1) - 1
    rho = (U - css / np.arange(1, k + 1) > 0).sum(1)
    theta = css[np.arange(len(flat)), rho - 1] / rho
    return np.maximum(flat - theta[:, None], 0).reshape(V.shape)


def fit_batch(A, C, iters=6000):
    """Batched min sum_i w_i ||y_i - x_i B_g||^2, rows of each B_g on the simplex. A=(G,K,K), C=(G,K,J)."""
    L = np.maximum(np.linalg.eigvalsh(A).max(1), 1e-12)[:, None, None]
    B = np.full(C.shape, 1 / C.shape[2])
    Z, t = B.copy(), 1.0
    for _ in range(iters):
        Bn = project_simplex(Z - (A @ Z - C) / L)
        tn = (1 + np.sqrt(1 + 4 * t * t)) / 2
        Z = Bn + (t - 1) / tn * (Bn - B)
        done = np.abs(Bn - B).max() < 1e-10
        B, t = Bn, tn
        if done:
            break
    return B


def fit_by_group(X, Y, members, mult=None):
    """One matrix per label, fitted on the units in members[label]; labels with no units are skipped."""
    labels = sorted(g for g, m in members.items() if m.any())
    w = X.sum(1) if mult is None else X.sum(1) * mult
    xs, ys = X / X.sum(1)[:, None], Y / Y.sum(1)[:, None]
    A = np.stack([(xs[members[g]] * w[members[g], None]).T @ xs[members[g]] for g in labels])
    C = np.stack([(xs[members[g]] * w[members[g], None]).T @ ys[members[g]] for g in labels])
    return dict(zip(labels, fit_batch(A, C)))


def ipf(T, rowt, colt, iters=5000, tol=0.01):
    """Rake each unit's table T[i] (R1 x R2) to its observed row and column totals (tol in votes)."""
    with np.errstate(invalid="ignore", divide="ignore"):
        for it in range(iters):
            T = T * np.nan_to_num(rowt / T.sum(2))[:, :, None]
            T = T * np.nan_to_num(colt / T.sum(1))[:, None, :]
            if it % 25 == 0 and np.abs(T.sum(2) - rowt).max() < tol:
                break
    return T


def flows(X, Y, groups, Bs, iters=5000, floor=SEED_FLOOR):
    B = np.stack([Bs[g] for g in groups])
    seed = X[:, :, None] * ((1 - floor) * B + floor / B.shape[2])
    return ipf(seed, X, Y, iters)


def wrmse(X, Y, groups, Bs, fallback):
    xs, ys = X / X.sum(1)[:, None], Y / Y.sum(1)[:, None]
    pred = np.stack([xs[i] @ Bs.get(g, fallback) for i, g in enumerate(groups)])
    w = X.sum(1)
    return np.sqrt((w[:, None] * (pred - ys) ** 2).sum(0) / w.sum())


def main():
    rows, X, Y = load(IN)
    states = np.array([r["uf"] for r in rows])
    regions = np.array([REGION[s] for s in states])
    G = groupings(rows, X)

    # split-half out-of-sample error of each grouping (simple random halves)
    oos = {k: [] for k in G}
    for _ in range(N_SPLITS):
        half = rng.random(len(rows)) < 0.5
        on_half = lambda members: {g: m[half] for g, m in members.items()}
        nat = fit_by_group(X[half], Y[half], on_half(G["national"][1]))["BR"]
        for k, (g, mem) in G.items():
            oos[k].append(wrmse(X[~half], Y[~half], g[~half], fit_by_group(X[half], Y[half], on_half(mem)), nat))
    oos = {k: np.mean(v, axis=0) for k, v in oos.items()}
    best = min(oos, key=lambda k: oos[k].mean())
    groups, members = G[best]

    Bs = {k: fit_by_group(X, Y, m) for k, (_, m) in G.items()}
    T = flows(X, Y, groups, Bs[best])
    F = T.sum(0)
    alt = {k: flows(X, Y, g, Bs[k]).sum(0) for k, (g, _) in G.items()}

    boot = np.zeros((N_BOOT,) + F.shape)
    for b in range(N_BOOT):
        mult = np.zeros(len(rows))
        for s in np.unique(states):
            idx = np.flatnonzero(states == s)
            mult[idx] = np.bincount(rng.integers(0, len(idx), len(idx)), minlength=len(idx))
        # 150 IPF sweeps leaves <100 votes of slack per unit: irrelevant at national scale, 7x faster
        boot[b] = flows(X, Y, groups, fit_by_group(X, Y, members, mult), iters=150).sum(0)
    lo, hi = np.percentile(boot, [5, 95], axis=0)

    os.makedirs(DATA, exist_ok=True)
    with open(os.path.join(DATA, f"transfer_national_{UNIT}.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["from_r1", "to_r2", "votes", "p5", "p95", "share_of_r1_row"] + [f"votes_{k}" for k in G])
        for i, a in enumerate(R1):
            for j, b in enumerate(R2):
                w.writerow([a, b, round(F[i, j]), round(lo[i, j]), round(hi[i, j]),
                            round(F[i, j] / F[i].sum(), 4)] + [round(alt[k][i, j]) for k in G])
    with open(os.path.join(DATA, f"transfer_by_state_{UNIT}.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["uf", "region", "from_r1", "to_r2", "votes", "share_of_r1_row"])
        for s in sorted(set(states)):
            Fs = T[states == s].sum(0)
            for i, a in enumerate(R1):
                for j, b in enumerate(R2):
                    w.writerow([s, REGION[s], a, b, round(Fs[i, j]), round(Fs[i, j] / max(Fs[i].sum(), 1), 4)])
    with open(os.path.join(DATA, f"transfer_by_unit_{UNIT}.csv"), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["uf", "tse_code", "name", "group"] + [f"{a} -> {b}" for a in R1 for b in R2])
        for r, g, t in zip(rows, groups, T):
            w.writerow([r["uf"], r["tse_code"], r["name"], g] + [round(v) for v in t.ravel()])
    summary = {
        "unit": UNIT, "n_units": len(rows), "grouping": best, "r1": R1, "r2": R2,
        "r1_totals": X.sum(0).round().tolist(), "r2_totals": Y.sum(0).round().tolist(),
        "flows": F.round().tolist(), "p5": lo.round().tolist(), "p95": hi.round().tolist(),
        "flows_by_grouping": {k: v.round().tolist() for k, v in alt.items()},
        "oos_wrmse": {k: v.round(5).tolist() for k, v in oos.items()},
        "by_region": {g: T[regions == g].sum(0).round().tolist() for g in sorted(set(regions))},
        "by_state": {s: T[states == s].sum(0).round().tolist() for s in sorted(set(states))},
    }
    json.dump(summary, open(os.path.join(DATA, f"transfer_summary_{UNIT}.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=1)

    mi = lambda v: f"{v / 1e6:5.2f}"
    print(f"units: {len(rows)} ({UNIT})   groups per grouping: " +
          ", ".join(f"{k} {len(set(g))}" for k, (g, _) in G.items()))
    print("Out-of-sample weighted RMSE of round-2 shares (pts of electorate):")
    for k, v in oos.items():
        print(f"  {k:22s} mean {100 * v.mean():.3f}  " + "  ".join(f"{b} {100 * e:.2f}" for b, e in zip(R2, v)))
    print(f"chosen: {best}   max |unit IPF residual|: row {np.abs(T.sum(2) - X).max():.2f} col {np.abs(T.sum(1) - Y).max():.2f}")
    print("\nNational flows, millions [90% bootstrap]  row-share   | same flow under: " + " / ".join(G))
    for i, a in enumerate(R1):
        print(f"{a:13s} {mi(X[:, i].sum())}M")
        for j, b in enumerate(R2):
            print(f"   -> {b:11s} {mi(F[i, j])} [{mi(lo[i, j])}, {mi(hi[i, j])}]  {F[i, j] / F[i].sum():6.1%}   | " +
                  " / ".join(mi(alt[k][i, j]) for k in G))
    print("\nBy region: share of each round-1 group going Lula/Flávio")
    for g in sorted(set(regions)):
        Fg = T[regions == g].sum(0)
        print(f"  {g:12s} " + "  ".join(
            f"{a[:6]} {Fg[i, 0] / Fg[i].sum():4.0%}/{Fg[i, 1] / Fg[i].sum():4.0%}" for i, a in enumerate(R1)))


if __name__ == "__main__":
    main()
