#!/usr/bin/env python3
"""MPD — external audit check. Standalone (Python 3.9+ standard library only): needs nothing from this repository except the
published CSV files, so a third party can run it against the data downloaded from hashflops.io.

For every sampled fact it re-downloads the cited SEC document and checks, independently of the MPD pipeline:
  A1 integrity  — SHA-256 of the canonical document bytes equals the sha256 column (canonical = the response with the one
                  <script src="/…"> tag that sec.gov's CDN appends before </body> removed; rule E-1 of the standard);
  A2 as filed   — the canonical length equals the document size in the EDGAR filing index (…/index.json);
  A3 evidence   — the number in the anchor occurs in the document text, next to the anchor's label words or inside its quote;
  A4 value      — the published value equals the number in the anchor (directly, or the stated derivation 'nM a − mM b' or a sum of
                  stated parts such as '520 + 124', whose first term must be in the anchor).
Class-B facts (evidence_class B-issuer-release: monthly releases the issuer publishes but does not file with the SEC) are checked
against the issuer's page: A1 compares the SHA-256 of the canonical release text (the release body, tags and scripts removed,
whitespace collapsed); a page edited since capture gives CHANGED, not FAIL — the Internet Archive copy listed in releases_b.csv
is then the reference; A2 does not apply; A3 and A4 as above.
Usage:
  SEC_USER_AGENT="Your Name your@email" python3 audit_verify.py production_monthly.csv [production_quarterly.csv …] [--n 30] [--all] [--seed 1]
Writes audit_report.csv next to the first input and prints a summary. Exit code 1 if any check fails.
SEC fair-access policy: identify yourself in SEC_USER_AGENT and keep the default pace (≈3 requests per second at most)."""
import csv, hashlib, html, json, os, random, re, sys, time, urllib.request
from html.parser import HTMLParser

UA = os.environ.get("SEC_USER_AGENT")
CDN_TAG = re.compile(rb'<script type="text/javascript"\s+src="/[A-Za-z0-9_\-/]+"></script>(?=\s*</body>)', re.I)
_last = [0.0]

def get(url, pace=0.35):
    w = pace - (time.time() - _last[0])
    if w > 0: time.sleep(w)
    _last[0] = time.time()
    req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Encoding": "identity"})
    with urllib.request.urlopen(req, timeout=90) as r: return r.read()

class Text(HTMLParser):
    def __init__(self): super().__init__(); self.parts = []; self.skip = 0
    def handle_starttag(self, tag, a):
        if tag in ("script", "style"): self.skip += 1
        if tag in ("td", "th", "p", "div", "br", "tr", "li"): self.parts.append(" ")
    def handle_endtag(self, tag):
        if tag in ("script", "style") and self.skip: self.skip -= 1
    def handle_data(self, d):
        if not self.skip: self.parts.append(d)
def text_of(b):
    t = Text(); t.feed(b.decode("utf-8", "ignore")); return re.sub(r"\s+", " ", html.unescape(" ".join(t.parts)))

CONTAINERS = [r'<div[^>]+class="[^"]*\bet_pb_post_content\b[^"]*"', r'<section[^>]+class="[^"]*\brelease-body\b[^"]*"', r'<article\b[^>]*>']
def _element(h, start):
    tag = re.match(r"<(\w+)", h[start:]).group(1).lower(); depth = 0
    for m in re.finditer(r"<(/?)" + tag + r"\b[^>]*>", h[start:], re.I):
        depth += -1 if m.group(1) else 1
        if depth == 0: return h[start:start + m.end()]
    return h[start:]
def release_text(b):
    """canonical text of an issuer release page (same definition as scripts/extract_classb.py)"""
    h = re.sub(r"(?is)<(script|style|noscript)\b.*?</\1>", " ", b.decode("utf-8", "replace"))
    for c in CONTAINERS:
        m = re.search(c, h, re.I)
        if m:
            e = _element(h, m.start())
            if len(e) > 1500: h = e; break
    return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", h))).strip()
def norm_num(s): return s.replace(",", "").strip("() ")
def check_release(r):
    out = {"issuer": r["issuer"], "period": r.get("month"), "value": r.get("value"), "url": r["url"], "A2": "SKIP"}
    t = release_text(get(r["url"], pace=1.0))
    out["A1"] = "PASS" if hashlib.sha256(t.encode()).hexdigest() == r.get("sha256") else "CHANGED"
    a = re.sub(r"\s+", " ", (r.get("anchor") or "").strip())
    key = re.sub(r"[^A-Za-z0-9]", "", a)[:120]
    out["A3"] = "PASS" if key and key in re.sub(r"[^A-Za-z0-9]", "", t) else ("CHANGED" if out["A1"] == "CHANGED" else "FAIL")
    nums = re.findall(r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?", a)
    out["A4"] = "PASS" if any(abs(float(norm_num(n)) - float(out["value"])) < 1e-6 for n in nums) else "FAIL"
    if "CHANGED" in (out["A1"], out["A3"]): out["note"] = "page edited since capture: compare the Internet Archive copy (releases_b.csv, wayback_url)"
    return out
def check_row(r, idx_cache):
    out = {"issuer": r["issuer"], "period": r.get("month") or r.get("quarter"), "value": r.get("value") or r.get("btc"), "url": r["url"]}
    if not r.get("url"): out.update(A1="SKIP", A2="SKIP", A3="SKIP", A4="SKIP", note="no document (override or standard anchor)"); return out
    if (r.get("evidence_class") or "").startswith("B-"): return check_release(r)
    b = get(r["url"]); c = CDN_TAG.sub(b"", b, count=1)
    out["A1"] = "SKIP" if not r.get("sha256") else ("PASS" if hashlib.sha256(c).hexdigest() == r["sha256"] else "FAIL")
    m = re.match(r"(https://www\.sec\.gov/Archives/edgar/data/\d+/\d+)/(.+)$", r["url"])
    size = None
    if m:
        if m.group(1) not in idx_cache:
            try: idx_cache[m.group(1)] = json.loads(get(m.group(1) + "/index.json"))
            except Exception: idx_cache[m.group(1)] = {}
        for it in (idx_cache[m.group(1)].get("directory") or {}).get("item", []):
            if it.get("name") == m.group(2) and str(it.get("size", "")).isdigit(): size = int(it["size"])
    out["A2"] = "SKIP" if size is None else ("PASS" if size == len(c) else "FAIL")
    t = text_of(c); a = r.get("anchor") or ""
    mt = re.match(r"\[(?:inline )?table\]\s*(.*?)\s*\|\s*.*?=\s*([-\d.,()]+)\s*$", a)
    if mt:                                   # table anchor: label words and the value must both be in the text, close together
        label, val = mt.group(1).split(" / ")[-1], mt.group(2)
        words = [w for w in re.findall(r"[A-Za-z]{3,}", label)][:4]
        pos = [x.start() for x in re.finditer(re.escape(words[0]), t, re.I)] if words else []
        hit = any(re.search(r"(?<![\d.])" + re.escape(val) + r"(?![\d])", t[p: p + 3000]) for p in pos)
        out["A3"] = "PASS" if hit else "FAIL"; nums = [val]
    elif a.startswith("[Cost per BTC standard"):
        out["A3"] = "SKIP"; nums = []
    else:                                    # sentence anchor: the quote itself must be in the text (whitespace-insensitive)
        q = re.sub(r"\s+", " ", a.strip(" |"))[:160]
        key = re.sub(r"[^A-Za-z0-9]", "", q)[:120]
        out["A3"] = "PASS" if key and key in re.sub(r"[^A-Za-z0-9]", "", t) else "FAIL"
        nums = re.findall(r"\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?", a)
    v = float(out["value"])
    der = (r.get("derivation") or "").strip()
    dv = re.match(r"\d+M ([\d.]+) − \d+M ([\d.]+)", der)
    if dv: out["A4"] = "PASS" if abs(float(dv.group(1)) - float(dv.group(2)) - v) < 0.011 else "FAIL"
    elif re.fullmatch(r"[\d.,]+(?:\s*[+−-]\s*[\d.,]+)+", der):   # stated parts added up, e.g. '520 + 124' or '2008 + 579 − 1570 − 485'
        terms = re.findall(r"([+−-]?)\s*([\d.,]+)", der)
        tot = sum((-1 if sg in ("−", "-") else 1) * float(norm_num(x)) for sg, x in terms)
        first = norm_num(terms[0][1])
        out["A4"] = "PASS" if abs(tot - v) < 0.011 and any(norm_num(n) == first for n in nums) else "FAIL"
    elif nums: out["A4"] = "PASS" if any(abs(float(norm_num(n)) - v) < 1e-6 for n in nums) else "FAIL"
    else: out["A4"] = "SKIP"
    return out

def main():
    if not UA: sys.exit("Set SEC_USER_AGENT to your name and e-mail (SEC fair-access policy).")
    args = sys.argv[1:]; files = [a for a in args if a.endswith(".csv")]
    n = int(args[args.index("--n") + 1]) if "--n" in args else 30
    seed = int(args[args.index("--seed") + 1]) if "--seed" in args else 1
    rows = []
    for f in files: rows += list(csv.DictReader(open(f, encoding="utf-8")))
    rows = [r for r in rows if r.get("url")]
    if "--all" not in args: random.Random(seed).shuffle(rows); rows = rows[:n]
    res = []; idx_cache = {}
    for i, r in enumerate(rows, 1):
        try: res.append(check_row(r, idx_cache))
        except Exception as e: res.append({"issuer": r["issuer"], "period": r.get("month") or r.get("quarter"), "url": r["url"], "A1": "ERROR", "note": str(e)[:200]})
        print(f"{i}/{len(rows)} {res[-1]['issuer']} {res[-1]['period']} " + " ".join(f"{k}={res[-1].get(k, '')}" for k in ("A1", "A2", "A3", "A4")), flush=True)
    fn = os.path.join(os.path.dirname(os.path.abspath(files[0])), "audit_report.csv")
    with open(fn, "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=["issuer", "period", "value", "A1", "A2", "A3", "A4", "url", "note"], extrasaction="ignore"); w.writeheader(); w.writerows(res)
    bad = [x for x in res if "FAIL" in (x.get("A1"), x.get("A2"), x.get("A3"), x.get("A4")) or x.get("A1") == "ERROR"]
    for k in ("A1", "A2", "A3", "A4"):
        c = {s: sum(1 for x in res if x.get(k) == s) for s in ("PASS", "FAIL", "CHANGED", "SKIP", "ERROR")}
        print(k, " ".join(f"{s}={v}" for s, v in c.items() if v))
    print(f"rows checked {len(res)}, rows with a failure {len(bad)} → {fn}")
    sys.exit(1 if bad else 0)

if __name__ == "__main__": main()
