"""Read the FEC files into aggregates per race, party and category. Payee, vendor and spender names are dropped on read.

Usage: python3 -I -B tools/pipeline.py <fec raw dir> <results dir>
Writes results/race_spend.csv, results/race_ie.csv, results/race_disb.csv, results/races.csv and results/coverage.json.
"""
import collections
import csv
import io
import json
import sys
import zipfile
from datetime import date, datetime
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(HERE))
import classify as C  # noqa: E402

PROTOCOL = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
CHANGES = json.loads((ROOT / "protocol-changes-r1.json").read_text(encoding="utf-8"))
Committee = collections.namedtuple("Committee", "cmte office state district party")
Candidate = collections.namedtuple("Candidate", "cand office state district party")
csv.field_size_limit(10_000_000)


def party(code):
    code = (code or "").strip().upper()
    if code in PROTOCOL["parties"]["D"]:
        return "D"
    if code in PROTOCOL["parties"]["R"]:
        return "R"
    return "other"


def label(margin):
    if margin is None:
        return "not_classified"
    return "close" if margin < 10 else "safe"


def parse_date(text):
    text = (text or "").strip()
    for fmt in ("%m/%d/%Y", "%d-%b-%y", "%d-%b-%Y", "%Y-%m-%d", "%m%d%Y"):
        try:
            return datetime.strptime(text, fmt).date()
        except ValueError:
            continue
    return None


def iso(text):
    return date.fromisoformat(text)


def read_zip_rows(path):
    with zipfile.ZipFile(path) as z:
        with z.open(z.namelist()[0]) as f:
            for line in io.TextIOWrapper(f, encoding="latin-1", newline="\n"):
                yield line.rstrip("\r\n").split("|")


def read_candidates(path, year):
    """cn file: id, name(dropped), party, election year, state, office, district."""
    out = {}
    for p in read_zip_rows(path):
        if len(p) < 7 or p[3] != str(year) or p[5] not in ("H", "S"):
            continue
        dist = "00" if p[5] == "S" else (p[6] or "00").zfill(2)
        out[p[0]] = Candidate(p[0], p[5], p[4], dist, party(p[2]))
    return out


def read_committees(path, cands, year):
    """ccl file: candidate id, candidate election year, fec year, committee id, type, designation, linkage id."""
    out = {}
    for p in read_zip_rows(path):
        if len(p) < 6 or p[1] != str(year) or p[0] not in cands or p[5] not in ("P", "A"):
            continue
        c = cands[p[0]]
        out[p[3]] = Committee(p[3], c.office, c.state, c.district, c.party)
    return out


def read_oppexp(path, committees, start, cutoff):
    """Field positions per the FEC file description: 0 committee, 1 amendment, 3 report type, 5 line, 6 form, 12 date,
    13 amount, 15 purpose, 16 filer's category, 18 memo code, 22 filing number, 23 transaction id. Position 8 (the payee) is
    never read."""
    start, cutoff = iso(start), iso(cutoff)
    best = {}
    counts = collections.Counter()
    max_date = None
    report_types = collections.defaultdict(set)
    purpose_other = collections.Counter()
    for p in read_zip_rows(path):
        if len(p) < 24:
            counts["short_rows"] += 1
            continue
        c = committees.get(p[0])
        if c is None:
            continue
        if p[6] != "F3" or not p[5].startswith("17"):
            counts["not_line_17"] += 1
            continue
        report_types[p[0]].add(p[3])
        if p[18] == "X":
            counts["memo_rows"] += 1
            continue
        d = parse_date(p[12])
        try:
            amt = float(p[13])
        except ValueError:
            counts["bad_amount"] += 1
            continue
        if d is None:
            counts["bad_date"] += 1
            continue
        if d.year <= cutoff.year and (max_date is None or d > max_date):
            max_date = d
        if not (start <= d <= cutoff):
            counts["outside_window"] += 1
            continue
        key = (p[0], p[23] or f"row{counts['rows']}")
        counts["rows"] += 1
        fn = int(p[22]) if p[22].isdigit() else 0
        if key in best:
            counts["duplicates_dropped"] += 1
            if fn <= best[key][0]:
                continue
        best[key] = (fn, c, amt, C.classify(p[15]), p[16] or "")
    amounts = collections.Counter()
    agree = collections.Counter()
    EXPECT = {"002": {"field"}, "003": {"fundraising"}, "004": {"media", "digital", "mail"}, "005": {"polling"},
              "006": {"mail"}, "007": {"field"}, "001": {"staff", "overhead", "consulting", "compliance", "polling"}}
    for fn, c, amt, cat, filer_cat in best.values():
        amounts[(c.office, c.state, c.district, c.party, cat)] += amt
        if filer_cat in EXPECT:
            agree["with_code"] += amt
            if cat in EXPECT[filer_cat]:
                agree["agree"] += amt
        agree["all"] += amt
    return {"amounts": amounts, "counts": counts, "max_date": max_date.isoformat() if max_date else None,
            "report_types": report_types, "agree": agree}


def read_ie(path, cands, start, election_day, cutoff, t34=None):
    """Independent expenditure CSV. Keeps one row per spender and transaction id: the highest filing number. Web-form rows
    (transaction id starting WFT) are excluded (Change 1); a blank expenditure date takes the dissemination date (Change 3)."""
    start, eday, cutoff = iso(start), iso(election_day), iso(cutoff)
    t34 = iso(t34) if t34 else cutoff
    web_dollars = 0.0
    web_best = {}
    best = {}
    counts = collections.Counter()
    max_rec = None
    max_exp = None
    with open(path, encoding="latin-1", newline="") as f:
        reader = csv.DictReader(f)
        fields = {k.strip().lower(): k for k in reader.fieldnames}
        g = lambda r, n: (r.get(fields.get(n, n)) or "").strip()  # noqa: E731
        for r in reader:
            cand = g(r, "can_id") or g(r, "cand_id")
            off = (g(r, "can_off") or g(r, "can_office")).upper()
            if off not in ("H", "S"):
                counts["not_house_senate"] += 1
                continue
            tran = g(r, "tra_id") or g(r, "tran_id")
            if tran.upper().startswith("WFT"):
                counts["web_form_rows"] += 1
                try:
                    wamt = float((g(r, "exp_amo") or "0").replace(",", "").replace("$", ""))
                except ValueError:
                    continue
                web_dollars += wamt
                # the same total after duplicates, as Change 1 measured it: highest filing number per spender and transaction
                wfn = int(g(r, "file_num")) if g(r, "file_num").isdigit() else 0
                wkey = (g(r, "spe_id"), tran)
                if wkey not in web_best or wfn > web_best[wkey][0]:
                    web_best[wkey] = (wfn, wamt)
                continue
            c = cands.get(cand)
            if c is not None:
                office, state, dist, pty = c.office, c.state, c.district, c.party
            else:
                office, state = off, (g(r, "can_off_sta") or g(r, "can_office_state")).upper()
                dist = "00" if off == "S" else (g(r, "can_off_dis") or g(r, "can_office_dis") or "00").zfill(2)[-2:]
                pty = party(g(r, "can_par_aff") or g(r, "cand_pty_aff"))
                counts["party_from_filer"] += 1
            d = parse_date(g(r, "exp_dat") or g(r, "exp_date"))
            if d is None:
                d = parse_date(g(r, "dissem_dt"))
                counts["date_from_dissemination"] += 1
            try:
                amt = float((g(r, "exp_amo") or "0").replace(",", "").replace("$", ""))
            except ValueError:
                counts["bad_amount"] += 1
                continue
            if d is None:
                counts["bad_date"] += 1
                continue
            rec = parse_date(g(r, "rec_dat") or g(r, "receipt_dat"))
            if rec and (max_rec is None or rec > max_rec):
                max_rec = rec
            sup = (g(r, "sup_opp") or "?").upper()[:1]
            fn_text = g(r, "file_num")
            fn = int(fn_text) if fn_text.isdigit() else 0
            key = (g(r, "spe_id"), tran or f"row{counts['rows']}")
            counts["rows"] += 1
            if key in best:
                counts["duplicates_dropped"] += 1
                if fn <= best[key][0]:
                    continue
            cat = C.classify(g(r, "pur"))
            typ = (g(r, "ele_typ") or g(r, "ele_type"))[:1].upper()
            best[key] = (fn, office, state, dist, pty, sup, cat, amt, d, typ)
    t20 = collections.Counter()
    t0 = collections.Counter()
    t20_general = collections.Counter()
    t34_table = collections.Counter()
    spenders_rows = 0
    for fn, office, state, dist, pty, sup, cat, amt, d, typ in best.values():
        spenders_rows += 1
        if d > eday or d < start:
            counts["outside_window"] += 1
            continue
        if max_exp is None or d > max_exp:
            max_exp = d
        t0[(office, state, dist, pty, sup, cat)] += amt
        if d <= t34:
            t34_table[(office, state, dist, pty, sup, cat)] += amt
        if d <= cutoff:
            t20[(office, state, dist, pty, sup, cat)] += amt
            if typ == "G":
                t20_general[(office, state, dist, pty, sup, cat)] += amt
    return {"t20": t20, "t0": t0, "t34": t34_table, "t20_general": t20_general, "counts": counts, "web_form_dollars": web_dollars,
            "web_form_dollars_after_duplicates": sum(v[1] for v in web_best.values()),
            "max_receipt": max_rec.isoformat() if max_rec else None, "max_exp": max_exp.isoformat() if max_exp else None}


def house_races(house_keys, pres, house_2024, new_lines, cycle):
    """House races of a cycle: every (state, district) with a candidate or money that is a real district of a state in the
    study, with its prior margin, or None where the lines changed (new-lines states in 2026, every state in 2022). A district
    number that does not exist in its state is a filer's mistyped or outdated number and is left out in every cycle (made
    uniform after the first figures were seen; see after-results-r1.json)."""
    out = {}
    for st, dist in sorted(house_keys):
        if st not in pres:  # territories and delegates are not in the study
            continue
        if f"{st}-{dist}" not in house_2024:
            continue
        out[("H", st, dist)] = None if cycle == "2022" or st in new_lines else house_2024[f"{st}-{dist}"]
    return out


def main():
    raw, res = Path(sys.argv[1]), Path(sys.argv[2])
    res.mkdir(parents=True, exist_ok=True)
    margins = json.loads((ROOT / "data" / "prior_margins.json").read_text(encoding="utf-8"))
    coverage = {}
    spend_rows, ie_rows, race_rows, disb_rows = [], [], [], []
    for cycle, cfg in PROTOCOL["cycles"].items():
        yy = cycle[2:]
        cands = read_candidates(raw / f"cn{yy}.zip", cycle)
        cmtes = read_committees(raw / f"ccl{yy}.zip", cands, cycle)
        t34 = CHANGES["cutoffs"][cycle]["t34"]
        op = read_oppexp(raw / f"oppexp{yy}.zip", cmtes, cfg["window_start"], CHANGES["cutoffs"][cycle]["mix"])
        ie = read_ie(raw / f"independent_expenditure_{cycle}.csv", cands, cfg["window_start"], cfg["election_day"], cfg["t20"], t34)
        # races: every Senate seat in the protocol and every House district with a candidate
        seats = PROTOCOL["senate_seats"][cycle]
        dropped = set(PROTOCOL["close_rule"]["senate_two_seats_excluded"].get(cycle, []))
        not_cls = set(PROTOCOL["close_rule"]["senate_not_classified"].get(cycle, {}))
        new_lines = set(PROTOCOL["close_rule"]["house_new_lines_2026"])
        pres = margins["president"]["2024" if cycle == "2026" else "2020"]
        races = {}
        for st in seats:
            m = margins["senate"][cycle][st]["margin"]
            races[("S", st, "00")] = None if st in not_cls else m
        house_keys = {(c.state, c.district) for c in cands.values() if c.office == "H"} | set()
        for key in list(op["amounts"]) + list(ie["t0"]):
            if key[0] == "H":
                house_keys.add((key[1], key[2]))
        races.update(house_races(house_keys, pres, margins["house_2024"], new_lines, cycle))
        for (off, st, dist), m in sorted(races.items()):
            race_rows.append({"cycle": cycle, "office": off, "state": st, "district": dist,
                              "prior_margin": "" if m is None else m, "label": label(m),
                              "state_president_margin": pres.get(st), "close_state": int(pres.get(st, 100) < 5)})
        kept = set(races)
        for (off, st, dist, pty, cat), amt in sorted(op["amounts"].items()):
            if (off, st, dist) in kept:
                spend_rows.append({"cycle": cycle, "office": off, "state": st, "district": dist, "party": pty,
                                   "category": cat, "dollars": round(amt, 2)})
            else:
                bucket = "senate_seat_left_out_spend" if off == "S" and st in dropped else "outside_any_race_spend"
                coverage.setdefault(cycle, {}).setdefault(bucket, 0.0)
                coverage[cycle][bucket] += amt
        for window, table in (("t20", ie["t20"]), ("t34", ie["t34"]), ("t0", ie["t0"]), ("t20_general", ie["t20_general"])):
            for (off, st, dist, pty, sup, cat), amt in sorted(table.items()):
                if (off, st, dist) not in kept:
                    if window == "t0":
                        coverage.setdefault(cycle, {}).setdefault("ie_outside_any_race", 0.0)
                        coverage[cycle]["ie_outside_any_race"] += amt
                else:
                    ie_rows.append({"cycle": cycle, "window": window, "office": off, "state": st, "district": dist, "party": pty,
                                    "direction": sup, "category": cat, "dollars": round(amt, 2)})
        ends = collections.Counter()
        disb = collections.defaultdict(lambda: [0.0, 0, ""])
        for p in read_zip_rows(raw / f"weball{yy}.zip"):
            c = cands.get(p[0])
            if c is None or (c.office, c.state, c.district) not in kept or len(p) < 28:
                continue
            ends[p[27]] += 1
            row = disb[(c.office, c.state, c.district, c.party)]
            row[0] += float(p[7] or 0)
            row[1] += 1
        for (off, st, dist, pty), (amt, n, _) in sorted(disb.items()):
            disb_rows.append({"cycle": cycle, "office": off, "state": st, "district": dist, "party": pty,
                              "total_disbursements": round(amt, 2), "candidates": n})
        coverage.setdefault(cycle, {})["summary_report_end_dates"] = ends.most_common(5)
        # who has a pre-general report: committees with any line 17 rows in the Q3 report, how many also filed the 12G
        rt = op["report_types"]
        q3 = [k for k, v in rt.items() if "Q3" in v]
        with_12g = [k for k in q3 if "12G" in rt[k]]
        last = {"cycle": cycle, "last_transaction_on_file": op["max_date"], "ie_last_receipt": ie["max_receipt"],
                "ie_last_expenditure": ie["max_exp"], "committees_with_q3": len(q3), "of_which_12g": len(with_12g),
                "candidates": len(cands), "committees": len(cmtes), "oppexp_counts": dict(op["counts"]),
                "ie_counts": dict(ie["counts"]), "web_form_dollars": round(ie["web_form_dollars"]),
                "web_form_dollars_after_duplicates": round(ie["web_form_dollars_after_duplicates"]),
                "agreement_with_filer_codes_pct": round(100 * op["agree"]["agree"] / op["agree"]["with_code"], 1) if op["agree"]["with_code"] else None,
                "share_with_filer_code_pct": round(100 * op["agree"]["with_code"] / op["agree"]["all"], 1) if op["agree"]["all"] else None}
        coverage.setdefault(cycle, {}).update(last)
        print(json.dumps({k: v for k, v in last.items() if not k.endswith("counts")}))
    for name, rows in (("race_spend", spend_rows), ("race_ie", ie_rows), ("races", race_rows), ("race_disb", disb_rows)):
        with open(res / f"{name}.csv", "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=list(rows[0]))
            w.writeheader()
            w.writerows(rows)
    (res / "coverage.json").write_text(json.dumps(coverage, indent=1) + "\n", encoding="utf-8")
    print(f"spend rows {len(spend_rows)}, ie rows {len(ie_rows)}, races {len(race_rows)}")


if __name__ == "__main__":
    main()
