"""Stream the source CSV into bin counts. Reads no vendor or buyer name and writes no row.

Usage: python3 -I -B tools/aggregate.py <contracts.csv> <output cells.json>
The output is counts per (department, fiscal year, commodity, period, route) and bin, kept outside the export. The public
histograms in results/ are sums of these with no department or route-by-year detail beyond what the page uses.
"""
import csv
import datetime as dt
import hashlib
import json
import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import bunching as bu  # noqa: E402

BEFORE_END = dt.date(2019, 6, 9)
AFTER_START, AFTER_END = dt.date(2019, 10, 1), dt.date(2025, 12, 14)
USED = ("procurement_id", "contract_date", "contract_value", "original_value", "amendment_value", "commodity_type",
        "solicitation_procedure", "instrument_type", "article_6_exceptions", "owner_org", "owner_org_title")
ROUTE = {"TN": "non_competitive", "AC": "non_competitive", "TC": "competitive", "OB": "competitive", "ST": "competitive"}


def money(s):
    s = (s or "").strip().replace(",", "").replace("$", "")
    if not s:
        return None
    try:
        return float(s)
    except ValueError:
        return None


def parse_date(s):
    s = (s or "").strip()[:10]
    try:
        return dt.date.fromisoformat(s)
    except ValueError:
        return None


def fiscal_year(d):
    """The calendar year a fiscal year starts in."""
    return d.year if d.month >= 4 else d.year - 1


def row_value(r):
    """The declared value rule. Returns (value, used the fallback)."""
    o, a, c = money(r["original_value"]), money(r["amendment_value"]), money(r["contract_value"])
    if o:
        return o, False
    if not a and c:
        return c, True
    return None, False


def main(path, out):
    # pass 1: coverage by fiscal year, reading no values
    cov, parse = {}, {"rows": 0, "not_C": 0, "bad_date": 0, "bad_commodity": 0, "no_value": 0}
    csv.field_size_limit(10 ** 7)
    with open(path, encoding="utf-8-sig", newline="") as f:
        for r in csv.DictReader(f):
            parse["rows"] += 1
            if (r.get("instrument_type") or "").strip() != "C":
                parse["not_C"] += 1
                continue
            d = parse_date(r.get("contract_date"))
            if d is None:
                parse["bad_date"] += 1
                continue
            ok = (r.get("commodity_type") or "").strip() in ("G", "S", "C")
            c = cov.setdefault(fiscal_year(d), [0, 0])
            c[0] += 1
            c[1] += int(ok)
    usable = sorted(y for y, (n, ok) in cov.items() if n >= 200 and ok / n >= 0.9 and y <= 2019)
    # the before period starts at the first fiscal year from which every later one up to the move also passes
    start = None
    for y in sorted(usable, reverse=True):
        if start is None or y == start - 1:
            start = y
    before_start = dt.date(start, 4, 1) if start is not None else None

    # pass 2: dedupe key -> earliest row, then count
    best = {}
    with open(path, encoding="utf-8-sig", newline="") as f:
        for i, r in enumerate(csv.DictReader(f)):
            if (r.get("instrument_type") or "").strip() != "C":
                continue
            d = parse_date(r.get("contract_date"))
            if d is None:
                continue
            ctype = (r.get("commodity_type") or "").strip()
            if ctype not in ("G", "S", "C"):
                parse["bad_commodity"] += 1
                continue
            v, fb = row_value(r)
            if v is None:
                parse["no_value"] += 1
                continue
            rid = (r.get("procurement_id") or "").strip()
            org = (r.get("owner_org") or "").strip()
            title = (r.get("owner_org_title") or "").split("|")[0].strip()
            rec = (d.isoformat(), v, fb, ctype, ROUTE.get((r.get("solicitation_procedure") or "").strip(), "unknown"),
                   (r.get("article_6_exceptions") or "").strip(), org, title)
            key = (org, hashlib.sha1(rid.encode()).hexdigest()) if rid else ("__row__", i)
            if key not in best or rec[0] < best[key][0]:
                if key in best:
                    parse["duplicates_removed"] = parse.get("duplicates_removed", 0) + 1
                best[key] = rec
            else:
                parse["duplicates_removed"] = parse.get("duplicates_removed", 0) + 1

    cells, titles = {}, {}
    tally = {"in_range": 0, "out_of_range": 0, "out_of_period": 0, "fallback_value_used": 0, "transition_excluded": 0}
    latest = None
    for d_s, v, fb, ctype, route, a6, org, title in best.values():
        d = dt.date.fromisoformat(d_s)
        if d <= AFTER_END and (latest is None or d > latest):
            latest = d
        if before_start and before_start <= d <= BEFORE_END:
            period = "before"
        elif AFTER_START <= d <= AFTER_END:
            period = "after"
        elif BEFORE_END < d < AFTER_START:
            tally["transition_excluded"] += 1
            continue
        else:
            tally["out_of_period"] += 1
            continue
        i = bu.bin_index(v)
        if i < 0:
            tally["out_of_range"] += 1
            continue
        tally["in_range"] += 1
        tally["fallback_value_used"] += int(fb)
        titles[org] = title
        k = f"{org}|{fiscal_year(d)}|{ctype}|{period}|{route}"
        c = cells.setdefault(k, {"n": {}, "exact": {}, "a6": {}, "sum": {}})
        si = str(i)
        c["n"][si] = c["n"].get(si, 0) + 1
        c["sum"][si] = round(c["sum"].get(si, 0.0) + v, 2)
        if abs(v - bu.EDGES[i]) < 0.005:
            c["exact"][si] = c["exact"].get(si, 0) + 1
        if a6 == "2":
            c["a6"][si] = c["a6"].get(si, 0) + 1
    res = {"coverage_by_fiscal_year": {str(y): {"C_rows": n, "valid_commodity": ok} for y, (n, ok) in sorted(cov.items())},
           "before_start": before_start.isoformat() if before_start else None, "parse": parse, "tally": tally,
           "latest_date_used": latest.isoformat() if latest else None, "org_titles": titles, "cells": cells}
    with open(out, "w", encoding="utf-8") as f:
        json.dump(res, f)
    print(json.dumps({k: res[k] for k in ("before_start", "parse", "tally", "latest_date_used")}))
    print("cells:", len(cells), "orgs:", len(titles))
    print("VERDICT: PASS" if tally["in_range"] else "VERDICT: FAIL no contracts in range")


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