#!/usr/bin/env python3
"""Compare, per caption: the answer written down first, the Koldflux Hashtag counter before and after the fix, and hashtag-check.py."""
import json, re, subprocess, sys, tempfile, os
d = sys.argv[1] if len(sys.argv) > 1 else "."
cases = json.load(open(f"{d}/tags.json"))
before = {r["id"]: r for r in json.load(open(f"{d}/live-before.json"))}
after = {r["id"]: r for r in json.load(open(f"{d}/fixed-after.json"))}
def script(text):
    with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as f:
        f.write(text); p = f.name
    out = subprocess.run([sys.executable, "-I", f"{d}/hashtag-check.py", p], capture_output=True, text=True).stdout
    os.unlink(p)
    m = re.match(r"hashtags: (\d+) \(unique, ignoring capitals: (\d+)\)", out)
    return int(m.group(1)), int(m.group(2))
print("case | expected total/unique | tool before fix | tool after fix | script | note shown (over 5) before/after")
ok_b = ok_a = ok_s = 0
for c in cases:
    exp = (c["expect"], c["expect_unique"])
    b = (before[c["id"]]["tool_tags"], before[c["id"]]["tool_unique"]); a = (after[c["id"]]["tool_tags"], after[c["id"]]["tool_unique"]); s = script(c["text"])
    ok_b += b == exp; ok_a += a == exp; ok_s += s == exp
    print(f'{c["id"]} | {exp[0]}/{exp[1]} | {b[0]}/{b[1]}{"" if b==exp else " MISMATCH"} | {a[0]}/{a[1]}{"" if a==exp else " MISMATCH"} | {s[0]}/{s[1]}{"" if s==exp else " MISMATCH"} | {before[c["id"]]["over_note"]}/{after[c["id"]]["over_note"]}')
n = len(cases)
print(f"matches expected: tool before fix {ok_b} of {n}; tool after fix {ok_a} of {n}; script {ok_s} of {n}")
# control: the over-5 note must be absent at 0 and 5 tags and present at 6 and above
ctrl = {k: after[k]["over_note"] for k in ("none", "five", "six-repeats", "thirty-one")}
print("control (over-5 note after fix):", ctrl, "PASS" if ctrl == {"none": False, "five": False, "six-repeats": True, "thirty-one": True} else "FAIL")
