#!/usr/bin/env python3
"""conditions.py 0.1.0: conditional claims vs the data they name (FINDINGS-2025, "Where disconnects can live", item 1).
Input: the hand encoding data/conditions/<year>.json (one entry per claim that carries a stated condition), the claims
(data/claims/<year>), the decisions (data/decisions/<year>.json and the first meeting of <year+1>), the as-known data
(data/vintage/<year>/<date>.json, ALFRED) and revised data (FRED csv files named in the encoding's "revised" map).
Per testable part: each measure compares the series as known at the next meeting with the same series as known at the
meeting where the words were spoken (window = data released between the two). The revised data are scored separately.
Outcomes: met | not_met | mixed (the measures disagree) | untestable (reason given). Action at the next meeting:
consistent | differs | no_action_named | not_compared | no_next_meeting. A candidate disconnect needs "differs" on a claim
whose wording requires the action (tie "requires"); it is worded only as "the statement and the policy differ on X".
A threshold is allowed only with threshold_words copied from the quote (never invented). Usage:
python3 -I tools/conditions.py 2025 > data/checks/2025-conditions.json   Last line (stderr): CONDITIONS ok ... | refused"""
import csv, json, os, sys

SERIES = {"UNRATE", "PAYEMS", "CPIAUCSL", "PCEPILFE"}
TRANSFORMS = {"level", "mom_change", "avg3_change", "yoy"}
TESTS = {"up", "down", "not_up", "not_down", "below", "above"}
ACTIONS = {"cut", "hold", "hike"}
ACTION = {"maintain": "hold", "lower": "cut", "raise": "hike"}


def month_back(d, k):
    y, m = int(d[:4]), int(d[5:7]) - k
    while m < 1:
        y, m = y - 1, m + 12
    return f"{y}-{m:02d}-01"


def transform(obs, d, how):
    """value of the transform at month d from {date: value}; None when a needed month is missing"""
    v = obs.get(d)
    if v is None:
        return None
    if how == "level":
        return v
    back = {"mom_change": 1, "avg3_change": 3, "yoy": 12}[how]
    p = obs.get(month_back(d, back))
    if p is None:
        return None
    if how == "yoy":
        return None if p == 0 else round(100.0 * (v / p - 1.0), 2)
    return round((v - p) / back, 1)


def latest(obs):
    pub = sorted(d for d, v in obs.items() if v is not None)
    return pub[-1] if pub else None


def judge(test, base, new, threshold=None):
    if new is None or (base is None and test not in ("below", "above")):
        return None
    if test in ("below", "above"):
        if threshold is None:
            return None
        return new < threshold if test == "below" else new > threshold
    return {"up": new > base, "down": new < base, "not_up": new <= base, "not_down": new >= base}[test]


def measure(m, known_then, known_next, revised):
    """one measure: as known (vintage then vs vintage at next meeting) and revised (same months, today's data)"""
    then, nxt = known_then[m["series"]], known_next[m["series"]]
    d0, d1 = latest(then), latest(nxt)
    row = {"series": m["series"], "transform": m["transform"], "test": m["test"], "base_month": d0, "new_month": d1}
    if "threshold" in m:
        row["threshold"] = m["threshold"]
    if d0 is None or d1 is None or d1 <= d0:
        row.update(as_known=None, revised=None, note="no new release between the two meetings")
        return row
    row["base"], row["new"] = transform(then, d0, m["transform"]), transform(nxt, d1, m["transform"])
    row["as_known"] = judge(m["test"], row["base"], row["new"], m.get("threshold"))
    rev = revised.get(m["series"])
    if rev is None:
        row["revised"] = None
    else:
        row["base_revised"], row["new_revised"] = transform(rev, d0, m["transform"]), transform(rev, d1, m["transform"])
        row["revised"] = judge(m["test"], row["base_revised"], row["new_revised"], m.get("threshold"))
    return row


def part_outcome(values):
    vals = [v for v in values if v is not None]
    if not vals:
        return "untestable"
    if all(vals):
        return "met"
    return "not_met" if not any(vals) else "mixed"


def combine(outcomes, how):
    if how == "all":
        order = ("not_met", "mixed", "untestable")
        for o in order:
            if o in outcomes:
                return o
        return "met"
    for o in ("met", "mixed", "untestable"):
        if o in outcomes:
            return o
    return "not_met"


def action_check(outcome, enc, did):
    if did is None:
        return "no_next_meeting"
    if outcome not in ("met", "not_met"):
        return "not_compared"
    allowed = enc.get("if_met") if outcome == "met" else enc.get("if_not_met")
    if not allowed:
        return "no_action_named"
    return "consistent" if did in allowed else "differs"


def validate(enc, claim):
    """problems with one encoding entry: the condition and its words must be the speaker's, thresholds must be quoted"""
    errs, cid = [], enc.get("claim_id")
    if claim is None:
        return [f"{cid}: no such claim"]
    if enc.get("scope") not in ("named_data", "no_named_data"):
        errs.append(f"{cid}: scope must be named_data or no_named_data")
    if enc.get("scope") == "no_named_data":
        if not enc.get("reason"):
            errs.append(f"{cid}: out of scope without a reason")
        return errs
    if enc.get("combine") not in ("all", "any"):
        errs.append(f"{cid}: combine must be all or any")
    if enc.get("tie") not in ("requires", "permits"):
        errs.append(f"{cid}: tie must be requires or permits")
    if enc.get("tie_words", "") not in claim["quote"] or not enc.get("tie_words"):
        errs.append(f"{cid}: tie_words not in the quote")
    for key in ("if_met", "if_not_met"):
        if enc.get(key) is not None and not set(enc[key]) <= ACTIONS:
            errs.append(f"{cid}: {key} holds an unknown action")
    if not enc.get("parts"):
        errs.append(f"{cid}: no parts")
    for p in enc.get("parts", []):
        if p.get("condition") not in claim["conditions"]:
            errs.append(f"{cid}: condition is not one of the claim's stated conditions")
        if not p.get("words") or p["words"] not in claim["quote"]:
            errs.append(f"{cid}: words not in the quote: {str(p.get('words'))[:50]}")
        if not p.get("testable"):
            if not p.get("reason"):
                errs.append(f"{cid}: untestable part without a reason")
            if p.get("measures"):
                errs.append(f"{cid}: untestable part with measures")
            continue
        if not p.get("measures"):
            errs.append(f"{cid}: testable part without measures")
        for m in p.get("measures", []):
            if m.get("series") not in SERIES or m.get("transform") not in TRANSFORMS or m.get("test") not in TESTS:
                errs.append(f"{cid}: bad measure {m}")
            if m.get("test") in ("below", "above"):
                if "threshold" not in m or not m.get("threshold_words") or m["threshold_words"] not in claim["quote"]:
                    errs.append(f"{cid}: threshold without the speaker's words")
            elif "threshold" in m:
                errs.append(f"{cid}: threshold on a direction test")
    return errs


def evaluate(enc, claim, meeting, nxt, vint, revised):
    """one encoded claim -> result row"""
    row = {"claim_id": enc["claim_id"], "meeting": meeting, "turn_seq": claim["turn_seq"], "quote": claim["quote"],
           "conditions": claim["conditions"], "scope": enc["scope"]}
    if enc["scope"] == "no_named_data":
        row.update(outcome="out_of_scope", reason=enc["reason"])
        return row
    did = ACTION[nxt["action"]] if nxt else None
    row.update(next_meeting=nxt["date"] if nxt else None, action=did, tie=enc["tie"], tie_words=enc["tie_words"],
               if_met=enc.get("if_met"), if_not_met=enc.get("if_not_met"), combine=enc["combine"], parts=[])
    known_then = vint.get(meeting)
    known_next = vint.get(nxt["date"]) if nxt else None
    for p in enc["parts"]:
        pr = {"condition": p["condition"], "words": p["words"], "testable": bool(p.get("testable"))}
        if not p.get("testable"):
            pr.update(as_known="untestable", revised="untestable", reason=p["reason"])
        elif known_then is None or known_next is None:
            pr.update(as_known="untestable", revised="untestable", reason="no as-known data for one of the two meetings")
        else:
            pr["measures"] = [measure(m, known_then, known_next, revised) for m in p["measures"]]
            pr["as_known"] = part_outcome([m["as_known"] for m in pr["measures"]])
            pr["revised"] = part_outcome([m["revised"] for m in pr["measures"]])
            if pr["as_known"] == "untestable":
                pr["reason"] = "no new release between the two meetings"
        row["parts"].append(pr)
    row["outcome"] = combine([p["as_known"] for p in row["parts"]], enc["combine"])
    row["outcome_revised"] = combine([p["revised"] for p in row["parts"]], enc["combine"])
    row["testable"] = any(p["testable"] for p in row["parts"])
    row["action_check"] = action_check(row["outcome"], enc, did)
    row["action_check_revised"] = action_check(row["outcome_revised"], enc, did)
    row["candidate"] = row["action_check"] == "differs" and enc["tie"] == "requires"
    if row["candidate"]:
        row["wording"] = (f"the statement and the policy differ on {enc.get('topic', 'the stated condition')}: the condition was "
                          f"{row['outcome'].replace('_', ' ')} in the data known on {nxt['date']}, and the Committee chose to {did}")
    return row


def check(encodings, claims, decisions, vint, revised):
    """encodings: list; claims: {meeting: [claim]}; decisions: dated list incl. the next year's first meeting"""
    by_id = {c["id"]: (m, c) for m, cs in claims.items() for c in cs}
    order = sorted(decisions, key=lambda d: d["date"])
    nxt = {order[i]["date"]: order[i + 1] for i in range(len(order) - 1)}
    errs, rows, seen = [], [], set()
    for enc in encodings:
        m, c = by_id.get(enc.get("claim_id"), (None, None))
        if enc.get("claim_id") in seen:
            errs.append(f"{enc.get('claim_id')}: encoded twice")
        seen.add(enc.get("claim_id"))
        e = validate(enc, c)
        errs += e
        if not e:
            rows.append(evaluate(enc, c, m, nxt.get(m), vint, revised))
    for cid, (m, c) in sorted(by_id.items()):
        if c["conditions"] and cid not in seen:
            errs.append(f"{cid}: claim with a stated condition is not encoded")
    return rows, errs


def summary(rows, errs):
    if errs:
        return f"CONDITIONS refused problems={len(errs)}"
    named = [r for r in rows if r["scope"] == "named_data"]
    test = [r for r in named if r["testable"]]
    count = lambda k, v: sum(1 for r in named if r[k] == v)
    return (f"CONDITIONS ok claims={len(rows)} named_data={len(named)} testable={len(test)} met={count('outcome', 'met')} "
            f"not_met={count('outcome', 'not_met')} mixed={count('outcome', 'mixed')} untestable={count('outcome', 'untestable')} "
            f"candidates={sum(1 for r in rows if r.get('candidate'))}")


def load(path):
    with open(path, encoding="utf-8") as f:
        return json.load(f)


def read_csv(path):
    with open(path, encoding="utf-8") as f:
        rows = list(csv.reader(f))
    return {r[0]: (None if r[1].strip() in (".", "") else float(r[1])) for r in rows[1:] if len(r) >= 2}


def run(year, root="."):
    j = lambda *p: load(os.path.join(root, *p))
    enc = j("data", "conditions", year + ".json")
    cdir = os.path.join(root, "data", "claims", year)
    claims = {f[:-5]: j("data", "claims", year, f)["claims"] for f in sorted(os.listdir(cdir)) if f.endswith(".json")}
    decisions = j("data", "decisions", year + ".json")
    nxt_year = os.path.join(root, "data", "decisions", str(int(year) + 1) + ".json")
    if os.path.exists(nxt_year):
        decisions = decisions + [min(load(nxt_year), key=lambda d: d["date"])]
    vint = {}
    for d in decisions:
        p = os.path.join(root, "data", "vintage", d["date"][:4], d["date"] + ".json")
        if os.path.exists(p):
            s = load(p)["series"]
            vint[d["date"]] = {k: {o[0]: o[1] for o in v["last13"]} for k, v in s.items()}
    revised = {k: read_csv(os.path.join(root, p)) for k, p in enc["revised"].items()}
    rows, errs = check(enc["claims"], claims, decisions, vint, revised)
    return {"tool": "conditions.py 0.1.0", "year": year, "revised_sources": enc["revised"], "rows": rows, "problems": errs}, summary(rows, errs)


if __name__ == "__main__":
    out, line = run(sys.argv[1])
    print(json.dumps(out, indent=1, ensure_ascii=False))
    print(line, file=sys.stderr)
    sys.exit(1 if out["problems"] else 0)
