#!/usr/bin/env python3
"""number_trace.py - check the numbers in a piece of text against source tables.

Local and offline: Python standard library only, no network, nothing is sent anywhere.

Usage:
    python number_trace.py --source tables.txt [more_tables.txt ...] --text draft.txt
                           [--ignore 0.05,0.15] [--no-rounding] [--no-percent]
                           [--verbose] [--out report.txt]

What it does:
  1. Pulls every number out of --text.
  2. Looks for each one in the --source file(s), allowing: leading zeros (.05 = 0.05),
     thousands commas, minus-sign variants, rounding to the number of decimals the text
     uses (half away from zero), and percent vs proportion (75.6% vs 0.756).
  3. Lists numbers it could not find, and numbers found only by rounding or by a
     percent/proportion conversion (so you can look at them).
  4. Lists strong or interpretive phrases in the text ("well tolerated",
     "statistically significant", ...) that do not appear in the source.

What it does NOT do: it proves a number appears somewhere in the source. It does not
prove the number is in the right row, column, arm or table, or that the wording is right.
A clean report is not a pass. See README.md.

Exit status: 0 nothing flagged, 1 something flagged, 2 usage or file error.
Licence: MIT.
"""
import argparse
import math
import os
import re
import sys

VERSION = "0.1.0"
TOL = 1e-9

NUM_RE = re.compile(
    r"(?<![A-Za-z0-9_.])-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?%?"
    r"|(?<![A-Za-z0-9_.])-?\.\d+%?"
)

# Label-like numbers that are not data (table ids, page cites, slide numbers, footnote marks).
LABEL_RES = [
    re.compile(r"\b(?:tables?|figures?|listings?|appendix|sections?|slides?|pages?|pp?\.)\s*\d+(?:[.\-]\d+)*", re.I),
    re.compile(r"(?<![A-Za-z0-9_.])\d+-\d+\.\d+\b"),
    re.compile(r"\[\d+(?:[,\-]\d+)*\]"),
]
LEADING_NUMBERING_RE = re.compile(r"^\s*\d+(?:\.\d+)*\.?\s+(?=[A-Za-z])")

# Strong or interpretive phrases. A hit is reported only if the same pattern is absent from the source.
PHRASES = [
    r"clinically (?:meaningful|relevant)", r"\b(?:statistically |clinically )?significant(?:ly)?\b",
    r"well[- ]tolerated", r"no (?:new )?safety (?:signals?|concerns?|issues?)",
    r"\bsafe(?:ly)?\b", r"demonstrat(?:e|es|ed|ing)", r"\bprov(?:e|es|ed|en|ing)\b",
    r"\bproof\b", r"\balways\b", r"\bnever\b", r"\bnone\b", r"\ball (?:patients|subjects|participants)\b",
    r"\bno (?:patients|subjects|participants)\b", r"\beffective(?:ness)?\b", r"\bsuperior(?:ity)?\b",
    r"\bbreakthrough\b", r"\bcaus(?:e|es|ed|ing)\b", r"\bdue to\b", r"\brelated to\b",
    r"\bimprov(?:e|es|ed|ement|ements|ing)\b", r"\bworsen(?:s|ed|ing)?\b", r"\bfavou?r(?:s|ed|able|ably)?\b",
    r"\bbenefit(?:s|ed)?\b", r"\bconsistent(?:ly)?\b", r"\brobust\b", r"\btrend(?:s|ing)?\b",
    r"\bclearly\b", r"\bconfirm(?:s|ed)?\b", r"\bpromising\b", r"\bremarkabl[ey]\b", r"\bexcellent\b",
    r"\bmostly\b", r"\bmost\b", r"\bfew\b", r"\bmajority\b", r"\bminimal\b", r"\bnegligible\b",
]
PHRASE_RES = [re.compile(p, re.I) for p in PHRASES]


def blank_labels(line, is_text):
    line = line.replace("−", "-").replace("–", "-").replace("—", "-")
    pats = LABEL_RES + ([LEADING_NUMBERING_RE] if is_text else [])
    for rx in pats:
        line = rx.sub(lambda m: " " * len(m.group(0)), line)
    return line


def parse_token(tok):
    pct = tok.endswith("%")
    t = tok.rstrip("%").replace(",", "")
    value = float(t)
    decimals = len(t.split(".")[1]) if "." in t else 0
    key = t + ("%" if pct else "")
    return value, decimals, pct, key


def extract(path_lines, is_text):
    """Return list of dicts: line, start, end, token, value, decimals, pct, key."""
    out = []
    for i, raw in enumerate(path_lines, start=1):
        cleaned = blank_labels(raw, is_text)
        for m in NUM_RE.finditer(cleaned):
            v, d, p, k = parse_token(m.group(0))
            out.append(dict(line=i, start=m.start(), end=m.end(), token=m.group(0),
                            value=v, decimals=d, pct=p, key=k))
    return out


def scaled_int(x, d):
    return int(math.floor(abs(x) * (10 ** d) + 0.5)) * (1 if x >= 0 else -1)


def half_up(x, d):
    r = int(math.floor(abs(x) * (10 ** d) + 0.5 + 1e-7))
    return r * (1 if x >= 0 else -1)


def candidates(src, use_pct):
    """(kind, value, decimals) variants of one source number."""
    s, ds = src["value"], src["decimals"]
    yield ("exact", s, ds, None)
    if use_pct:
        if abs(s) <= 1:
            yield ("percent", s * 100, max(ds - 2, 0), True)   # proportion in source, percent in text
        if 0 <= s <= 100:
            yield ("percent", s / 100, ds + 2, False)          # percent in source, proportion in text


RANK = {"exact": 0, "rounded": 1, "percent": 2, "percent+rounded": 3}


def best_match(num, sources, rounding, use_pct, negate=False):
    t = -num["value"] if negate else num["value"]
    dt = num["decimals"]
    best = None
    for src in sources:
        for kind, c, dc, needs_pct in candidates(src, use_pct):
            if needs_pct is True and not num["pct"]:
                continue
            if needs_pct is False and num["pct"]:
                continue
            if dc == dt and scaled_int(c, dc) == scaled_int(t, dt):
                k = kind
            elif rounding and dc > dt and half_up(c, dt) == scaled_int(t, dt):
                k = "rounded" if kind == "exact" else "percent+rounded"
            else:
                continue
            if best is None or RANK[k] < RANK[best[0]]:
                best = (k, src)
    return best


def context(line, start, end, width=25):
    a, b = max(0, start - width), min(len(line), end + width)
    return re.sub(r" +", " ", line[a:b].replace("\t", " ")).strip()


def run(source_paths, text_path, ignore, rounding, use_pct, verbose):
    src_names, sources, seen = [], [], set()
    for p in source_paths:
        name = os.path.basename(p)
        src_names.append(name)
        with open(p, encoding="utf-8-sig", newline="") as f:
            lines = f.read().replace("\r\n", "\n").replace("\r", "\n").split("\n")
        for n in extract(lines, False):
            if n["key"] not in seen:
                seen.add(n["key"])
                n["where"] = "%s line %d" % (name, n["line"])
                sources.append(n)
    with open(text_path, encoding="utf-8-sig", newline="") as f:
        tlines = f.read().replace("\r\n", "\n").replace("\r", "\n").split("\n")
    nums = extract(tlines, True)
    all_src_text = "\n".join(
        open(p, encoding="utf-8-sig", newline="").read() for p in source_paths)

    counts = dict(exact=0, percent=0, rounded=0, allowed=0, notfound=0)
    notfound, look, found_rows, weak = [], [], [], 0
    for n in nums:
        if any(abs(n["value"] - g) < TOL for g in ignore):
            counts["allowed"] += 1
            continue
        m = best_match(n, sources, rounding, use_pct)
        if m is None:
            counts["notfound"] += 1
            note = ""
            flip = best_match(n, sources, False, use_pct, negate=True)
            if flip is not None:
                note = '  [source has "%s" with the opposite sign (%s)]' % (flip[1]["token"], flip[1]["where"])
            notfound.append((n, note))
            continue
        kind, src = m
        if kind == "exact":
            counts["exact"] += 1
            if n["decimals"] == 0 and not n["pct"] and abs(n["value"]) < 10:
                weak += 1
            if verbose:
                found_rows.append((n, kind, src))
        else:
            counts["percent" if kind == "percent" else "rounded"] += 1
            look.append((n, kind, src))
            if verbose:
                found_rows.append((n, kind, src))

    phrase_hits = []
    for i, raw in enumerate(tlines, start=1):
        for rx in PHRASE_RES:
            if rx.search(all_src_text):
                continue
            for m in rx.finditer(raw):
                phrase_hits.append((i, m.start(), m.group(0), context(raw, m.start(), m.end(), 30)))
    phrase_hits.sort(key=lambda h: (h[0], h[1]))

    distinct = len({n["key"] for n in nums})
    o = []
    o.append("number_trace %s (local, offline)" % VERSION)
    o.append("source files: " + ", ".join(src_names))
    o.append("text file: " + os.path.basename(text_path))
    o.append("rounding: %s   percent/proportion: %s" % ("on" if rounding else "off", "on" if use_pct else "off"))
    o.append("")
    o.append("SUMMARY")
    o.append("numbers in text: %d (%d distinct)" % (len(nums), distinct))
    o.append("  found exactly: %d" % counts["exact"])
    o.append("  found as percent/proportion only: %d" % counts["percent"])
    o.append("  found after rounding only: %d" % counts["rounded"])
    o.append("  allowed with --ignore: %d" % counts["allowed"])
    o.append("  NOT FOUND: %d" % counts["notfound"])
    o.append("  (single-digit integers found exactly, easy to match by chance: %d)" % weak)
    o.append("strong or interpretive phrases not in the source: %d" % len(phrase_hits))
    o.append("")
    o.append("NOT FOUND IN SOURCE")
    if notfound:
        for n, note in notfound:
            o.append('  line %d  "%s"  ...%s...%s' % (n["line"], n["token"],
                     context(tlines[n["line"] - 1], n["start"], n["end"]), note))
    else:
        o.append("  none")
    o.append("")
    o.append("FOUND ONLY BY ROUNDING OR PERCENT/PROPORTION (check these by eye)")
    if look:
        for n, kind, src in look:
            o.append('  line %d  "%s"  matches source "%s" (%s) by %s' % (
                n["line"], n["token"], src["token"], src["where"], kind))
    else:
        o.append("  none")
    o.append("")
    o.append("STRONG OR INTERPRETIVE PHRASES NOT IN THE SOURCE")
    if phrase_hits:
        for ln, _st, ph, ctx in phrase_hits:
            o.append('  line %d  "%s"  ...%s...' % (ln, ph, ctx))
    else:
        o.append("  none")
    if verbose:
        o.append("")
        o.append("ALL MATCHED NUMBERS")
        for n, kind, src in found_rows:
            o.append('  line %d  "%s"  -> "%s" (%s) %s' % (n["line"], n["token"], src["token"], src["where"], kind))
    o.append("")
    o.append("Limits: a number found here appears somewhere in the source. This does not show it is the")
    o.append("right number, in the right row, column, arm or table, or that the wording is correct.")
    flagged = counts["notfound"] > 0 or len(phrase_hits) > 0
    return "\n".join(o) + "\n", flagged


def main(argv=None):
    ap = argparse.ArgumentParser(description="Check numbers in text against source tables (offline).")
    ap.add_argument("--source", nargs="+", required=True, help="source table file(s), text or CSV")
    ap.add_argument("--text", required=True, help="the text to check")
    ap.add_argument("--ignore", default="", help="comma-separated numbers to accept, e.g. 0.05,0.15")
    ap.add_argument("--no-rounding", action="store_true")
    ap.add_argument("--no-percent", action="store_true")
    ap.add_argument("--verbose", action="store_true", help="also list every matched number")
    ap.add_argument("--out", help="write the report to this file (UTF-8, LF)")
    try:
        a = ap.parse_args(argv)
    except SystemExit as e:
        return 2 if e.code else 0
    try:
        ignore = [float(x) for x in a.ignore.split(",") if x.strip()]
        report, flagged = run(a.source, a.text, ignore, not a.no_rounding, not a.no_percent, a.verbose)
    except (OSError, ValueError) as e:
        sys.stderr.write("number_trace: %s\n" % e)
        return 2
    if a.out:
        with open(a.out, "w", encoding="utf-8", newline="\n") as f:
            f.write(report)
    else:
        sys.stdout.buffer.write(report.encode("utf-8"))
    return 1 if flagged else 0


if __name__ == "__main__":
    sys.exit(main())
