#!/usr/bin/env python3
"""measurability.py 0.1.1: how measurable the FOMC's forward guidance is, statement by statement (docs/ENCODING.md,
"Guidance measurability 0.1"). Reads the numbered sentences made by statements.py (data/text/<year>/statement<date>-html.txt)
and the statement list (data/raw/<year>/statements.json, for the unscheduled flag).

  python3 -I tools/measurability.py encode 2008 2025   -> data/guidance/<year>.json (every guidance sentence, verbatim, level, rule)
  python3 -I tools/measurability.py report 2008 2025   -> data/checks/measurability-2008-2025.json and the success line

Levels: T3 explicit numeric threshold on a named series, or an explicit date; T2 a named series with a direction but no
threshold; T1 a general reference to data or outcomes; T0 no condition. Rules are applied in order T3, T2, T1, T0; the first
that fires sets the level. Manual review lives in data/guidance/overrides.json ({"<date>-sNN": {"level"|"guidance", "note"}}):
every override needs a note, and an override may only lower a level or remove a sentence (when unsure, the lower level)."""
import json, os, re, sys

LEVELS = ["T0", "T1", "T2", "T3"]

# G: forward guidance = a policy object + a forward marker, unless an exclusion fires.
POLICY = re.compile(r"federal funds rate|target range|policy rate|monetary policy|stance of (?:monetary )?policy|policy accommodation"
                    r"|policy stance|accommodation|firming|purchas(?:e|es|ed|ing)\b(?! power)|holdings|securities|balance sheet|reinvest\w*|runoff|redemption|rate increases"
                    r"|policy tools|its tools|these tools|available tools|range of tools|adjustments to (?:the|its)"
                    r"|\bact (?:in a timely manner|promptly|as needed|as appropriate|to)\b", re.I)
FORWARD = re.compile(r"\bwill\b|\bwould\b|anticipat\w*|\bexpects?\b|\bintends?\b|\blikely\b|\bprepared\b|stands? ready|going forward"
                     r"|\bfuture\b|coming (?:months|meetings|quarters)|for some time|extended period|considerable (?:time|period)"
                     r"|at least through|\buntil\b|as long as|in determining|in considering|in assessing|be patient|this year|next year"
                     r"|by the end of|through the end of|over the next|per month|at a pace of|beginning (?:in|on)|scheduled to|\bunlikely\b"
                     r"|wait for", re.I)
# X1: the policy words sit only inside an outlook clause ("with appropriate policy accommodation, growth will ...").
OUTLOOK_CLAUSE = re.compile(r"(?:with|without)\s+(?:sufficient\s+|appropriate\s+|continued\s+)?(?:policy accommodation|monetary policy"
                            r"(?: accommodation)?|policy firming|firming of policy|accommodation|firming in the stance of monetary policy)"
                            r"|(?:support|help) from monetary policy", re.I)
GRADUAL = re.compile(r"with (?:further |some further )?gradual (?:adjustments|increases)|gradual increases in the target range for the federal"
                     r" funds rate will be consistent with", re.I)
# X2: goal statements; X3: statements of what past actions will or should do.
GOAL = re.compile(r"^(?:Consistent with its statutory mandate, )?The Committee seeks to|strongly committed to", re.I)
EFFECT = re.compile(r"(?:action|actions|measures|purchases|policy action)s?\b[^.]{0,80}?\b(?:should|will) (?:help|promote|foster|support"
                    r"|maintain|contribute|put)", re.I)

# T3-D: an explicit date (a year, a part of a named year, a quarter, a named month, the end of this or next year).
MONTH = r"(?:January|February|March|April|May|June|July|August|September|October|November|December)"
DATE = re.compile(r"\b20\d\d\b|\b(?:mid|late|early)-20\d\d|\b(?:first|second|third|fourth) quarter\b|\b(?:end of|by the end of) "
                  r"(?:the|this|next|the current) (?:year|quarter|month)\b|\bthis year\b|\bnext year\b|\bby autumn\b|\blater this (?:month|year)\b"
                  r"|\b(?:in|beginning in|beginning on|on|through|by|end of) " + MONTH + r"\b|\b" + MONTH + r" \d{1,2}\b"
                  r"|\b(?:at|by) (?:the|its) " + MONTH + r" (?:FOMC )?meeting", re.I)
# A date that names the past (a document issued then, a period already over, a program initiated or begun then) is not a
# condition on the future (0.1.1 adds initiated / began / begun / started: 2017-11-01 s19, review of 2026-11-08).
PAST_BEFORE = re.compile(r"(?:issued|announced|adopted|released|described|during|since|prevailed|earlier than|initiated|began|begun|started)\s+(?:\S+\s+){0,3}$", re.I)
PAST_AFTER = re.compile(r"^\s*(?:20\d\d\s+)?(?:Addendum|Plans|Principles|statement)", re.I)


def forward_date(s):
    """The first DATE match that does not name the past, or None."""
    for m in DATE.finditer(s):
        if PAST_BEFORE.search(s[max(0, m.start() - 40):m.start()]) or PAST_AFTER.search(s[m.end():]):
            continue
        return m
    return None


# T3-N: a trigger, then a comparison with a number on a named series.
TRIGGER = re.compile(r"\buntil\b|as long as|\bprovided\b|\bif\b|\bonce\b", re.I)
NUMERIC = re.compile(r"(?:remains? above|remains? below|\babove\b|\bbelow\b|exceed\w*|no more than|risen to|rises? to|reached|falls? to"
                     r"|moves? (?:above|below))[^,;]{0,60}?(?:\d[\d/-]*|one|a half|half a) (?:percent|percentage point)", re.I)
HEDGED = re.compile(r"especially if|particularly if", re.I)
GOAL_NUMBER = re.compile(r"(?:return|returning|bring|bringing)\s+inflation\s+(?:back\s+)?to\s+(?:its\s+)?2 percent|2 percent (?:objective|goal)"
                         r"|inflation of 2 percent|2 percent inflation|2 percent over time|2 percent over the longer run", re.I)
# Before the T2 test: purpose clauses ("to promote ...") and references to the Committee's goals are not conditions
# ("on track to achieve ..." is a condition and "expects to maintain ..." is the plan itself, so those are kept).
PURPOSE = re.compile(r"(?<!track )(?<!expects )(?<!expect )(?<!intends )(?<!decided )(?<!agreed )(?<!continue )"
                     r"\b(?:[Tt]o|in order to) (?:support|promote|foster|help|achieve|sustain|provide|preserve|maintain|ensure|attain"
                     r"|return|bring|mitigate|improve|facilitate)\b(?:(?! as | if | until | when | provided )[^,;])*(?:, with [^,;]*)?|\bIn support of (?:its|these|the Committee's) goals", re.I)
GOAL_REF = re.compile(r"(?:its |the Committee['’]s )?(?:longer-run )?(?:objectives?|goals?) of maximum employment and (?:2 percent inflation"
                      r"|price stability|inflation of 2 percent|inflation at the rate of 2 percent)|maximum employment and price stability"
                      r"|maximum employment and (?:2 percent )?inflation|(?:its |the Committee['’]s )?(?:employment and inflation |dual )?"
                      r"(?:longer-run )?(?:2 percent )?(?:objectives?|goals?|mandate)|mandate-consistent levels"
                      r"|levels (?:that )?(?:the Committee judges )?consistent with its (?:dual )?mandate|price stability", re.I)
WINDOW = 6
# T2: a named series with a direction within WINDOW words of it.
SERIES = re.compile(r"inflation|unemployment|employment|job gains|payroll|labor market|resource utilization|resource slack|economic growth"
                    r"|economic activity|\bgrowth\b|\boutput\b", re.I)
DIRECTION = re.compile(r"improv\w*|\brise\w*|\brisen\b|rising|increas\w*|declin\w*|\bfall\w*|moderat\w*|strengthen\w*|weaken\w*|toward"
                       r"|\breturn\w*|exceed\w*|\babove\b|\bbelow\b|subdued|\blow\b|\bhigh\b|elevated|\bstable\b|anchored|sustainabl\w*"
                       r"|progress|on track|picks? up|slow\w*|deteriorat\w*|move back|moving back|\bnear\b|well past", re.I)
# T1: a general reference to data or outcomes.
GENERAL = re.compile(r"incoming|\bdata\b|information|outlook|\brisks?\b|developments|conditions|evolv\w*|as appropriate|as needed"
                     r"|\bwarrant\w*|\bgoals?\b|objectives?|mandate|circumstances|economic|progress|efficacy|costs|outcomes", re.I)
BALANCE = re.compile(r"purchas\w*|holdings|securities|balance sheet|reinvest\w*|runoff|redemption", re.I)
RATE = re.compile(r"federal funds rate|target range|policy rate|rate increases|firming|accommodation|stance", re.I)


def is_guidance(s):
    """(True, rule) or (False, rule)."""
    if GOAL.search(s):
        return False, "X2"
    if EFFECT.search(s):
        return False, "X3"
    if not FORWARD.search(s) and not forward_date(s):
        return False, "none"
    if not POLICY.search(s):
        return False, "none"
    if not POLICY.search(OUTLOOK_CLAUSE.sub(" ", s)):
        return False, "X1"
    return True, "G"


def series_direction(s):
    """The first named series with a direction word within WINDOW words on either side, as "series / direction", or ""."""
    for m in SERIES.finditer(s):
        ctx = " ".join(s[:m.start()].split()[-WINDOW:] + [m.group(0)] + s[m.end():].split()[:WINDOW])
        d = DIRECTION.search(ctx)
        if d:
            return m.group(0) + " / " + d.group(0)
    return ""


def classify(s):
    """(level, rule, matched words)."""
    if GRADUAL.search(s) and OUTLOOK_CLAUSE.search(s) is None and not forward_date(s) and not TRIGGER.search(s):
        return "T0", "T0-F", GRADUAL.search(s).group(0)
    m = forward_date(s)
    if m:
        return "T3", "T3-D", m.group(0)
    clean = GOAL_NUMBER.sub(" ", s)
    m = NUMERIC.search(clean)
    if m and TRIGGER.search(clean[:m.start()]) and SERIES.search(clean):
        if HEDGED.search(clean[:m.start()]):
            return "T2", "T2-H", m.group(0)
        return "T3", "T3-N", m.group(0)
    sd = series_direction(GOAL_REF.sub(" ", PURPOSE.sub(" ", s)))
    if sd:
        return "T2", "T2", sd
    m = GENERAL.search(PURPOSE.sub(" ", s))
    if m:
        return "T1", "T1", m.group(0)
    return "T0", "T0", ""


def subject(s):
    b, r = bool(BALANCE.search(s)), bool(RATE.search(s))
    return "balance_sheet" if b and not r else "rate" if r and not b else "both" if b and r else "general"


def read_sentences(path):
    out = []
    for line in open(path, encoding="utf-8"):
        line = line.rstrip("\n")
        if line:
            idx, _, s = line.partition("\t")
            out.append((idx, s))
    return out


def encode_statement(date, sents, unscheduled=False, overrides=None):
    """Every guidance sentence of one statement, with its level; overrides applied (lower or remove only)."""
    overrides = overrides or {}
    out = []
    for idx, s in sents:
        g, grule = is_guidance(s)
        if not g:
            continue
        level, rule, words = classify(s)
        rec = {"id": f"{date}-{idx}", "date": date, "sentence": idx, "quote": s, "level": level, "rule": rule, "matched": words,
               "subject": subject(s), "unscheduled": unscheduled}
        o = overrides.get(rec["id"])
        if o:
            if not o.get("note"):
                raise ValueError("override without a note: " + rec["id"])
            if o.get("guidance") is False:
                continue
            if "level" in o:
                if LEVELS.index(o["level"]) > LEVELS.index(level):
                    raise ValueError("override may only lower a level: " + rec["id"])
                rec.update(level=o["level"], rule="override", note=o["note"])
        out.append(rec)
    return out


def share(n, d):
    return round(n / d, 3) if d else None


def summarize(recs, statements):
    """Counts and shares for a set of guidance sentences drawn from `statements` (a list of dates)."""
    c = {lv: sum(r["level"] == lv for r in recs) for lv in LEVELS}
    n = len(recs)
    t3_dates = sorted({r["date"] for r in recs if r["level"] == "T3"})
    rate = [r for r in recs if r["subject"] in ("rate", "both")]
    with_g = {r["date"] for r in recs}
    return {"statements": len(statements), "statements_without_guidance": sum(d not in with_g for d in statements), "sentences": n, **{lv.lower(): c[lv] for lv in LEVELS},
            **{lv.lower() + "_share": share(c[lv], n) for lv in LEVELS},
            "statements_with_t3": len(t3_dates), "rate_sentences": len(rate),
            "rate_t3": sum(r["level"] == "T3" for r in rate), "rate_t3_share": share(sum(r["level"] == "T3" for r in rate), len(rate)),
            "statements_with_rate_t3": len({r["date"] for r in rate if r["level"] == "T3"})}


# Chair terms from the Board's membership page (data/context/raw/2026-11-08/fed-board-membership.htm).
# Powell's era ends the day before May 22, 2026 (no meeting fell on either day).
CHAIRS = [("Bernanke", "20060201", "20140131"), ("Yellen", "20140203", "20180203"), ("Powell", "20180205", "20260521"),
          ("Warsh", "20260522", "99991231")]


def runs(dates, flagged):
    """Maximal runs of consecutive statements (in `dates` order) that are all in `flagged`: [(first, last, count)]."""
    out, cur = [], []
    for d in dates:
        if d in flagged:
            cur.append(d)
        elif cur:
            out.append((cur[0], cur[-1], len(cur))); cur = []
    if cur:
        out.append((cur[0], cur[-1], len(cur)))
    return out


def report(by_year):
    """by_year: {year: {"statements": [dates of scheduled statements], "records": [...]}} -> result dict.
    Shares count scheduled statements only; unscheduled ones are counted apart."""
    years, allrecs, alldates, unsched = {}, [], [], []
    for y in sorted(by_year):
        recs = [r for r in by_year[y]["records"] if not r["unscheduled"]]
        unsched += [r for r in by_year[y]["records"] if r["unscheduled"]]
        years[str(y)] = summarize(recs, by_year[y]["statements"])
        allrecs += recs
        alldates += by_year[y]["statements"]
    alldates.sort()
    eras = {}
    for name, a, b in CHAIRS:
        ds = [d for d in alldates if a <= d <= b]
        if ds:
            eras[name] = {"from": ds[0], "to": ds[-1], **summarize([r for r in allrecs if a <= r["date"] <= b], ds)}
    t3_any = {r["date"] for r in allrecs if r["level"] == "T3"}
    t3_rate = {r["date"] for r in allrecs if r["level"] == "T3" and r["subject"] in ("rate", "both")}
    return {"years": years, "chair_eras": eras, "all": summarize(allrecs, alldates),
            "t3_runs_any": [{"from": a, "to": b, "statements": n} for a, b, n in runs(alldates, t3_any)],
            "t3_runs_rate": [{"from": a, "to": b, "statements": n} for a, b, n in runs(alldates, t3_rate)],
            "unscheduled": {"sentences": len(unsched), "t3": sum(r["level"] == "T3" for r in unsched)}}


def success_line(res, y0, y1):
    a = res["all"]
    return (f"MEASURABILITY years={len(res['years'])} span={y0}-{y1} statements={a['statements']} sentences={a['sentences']} "
            f"t3={a['t3_share']} t2={a['t2_share']} t1={a['t1_share']} t0={a['t0_share']} rate_t3={a['rate_t3_share']} "
            f"t3_runs_rate={len(res['t3_runs_rate'])}")


def load_overrides(root):
    p = os.path.join(root, "guidance", "overrides.json")
    return json.load(open(p)) if os.path.exists(p) else {}


def encode_year(y, root="data"):
    meta = json.load(open(os.path.join(root, "raw", str(y), "statements.json")))
    ov = load_overrides(root)
    recs = []
    for item in meta:
        sents = read_sentences(os.path.join(root, "text", str(y), f"statement{item['date']}-html.txt"))
        recs += encode_statement(item["date"], sents, item["unscheduled"], ov)
    return {"year": y, "statements": [i["date"] for i in meta if not i["unscheduled"]],
            "unscheduled": [i["date"] for i in meta if i["unscheduled"]], "records": recs}


def main(argv, root="data"):
    cmd, y0, y1 = argv[0], int(argv[1]), int(argv[2])
    if cmd == "encode":
        os.makedirs(os.path.join(root, "guidance"), exist_ok=True)
        for y in range(y0, y1 + 1):
            with open(os.path.join(root, "guidance", f"{y}.json"), "w") as f:
                json.dump(encode_year(y, root), f, indent=1, ensure_ascii=False)
        return f"MEASURABILITY encoded years={y1 - y0 + 1}"
    if cmd == "report":
        by_year = {y: json.load(open(os.path.join(root, "guidance", f"{y}.json"))) for y in range(y0, y1 + 1)}
        res = report(by_year)
        res["method"] = "tools/measurability.py 0.1.1; rules docs/ENCODING.md 'Guidance measurability 0.1'; scheduled statements only"
        os.makedirs(os.path.join(root, "checks"), exist_ok=True)
        with open(os.path.join(root, "checks", f"measurability-{y0}-{y1}.json"), "w") as f:
            json.dump(res, f, indent=1)
        return success_line(res, y0, y1)
    raise SystemExit("usage: measurability.py encode|report <first year> <last year>")


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