"""Score the simple tier (one memo, W01). Usage: grade_simple.py <lang> <note.md> [--json out.json]"""
import json, re, sys
from pathlib import Path
from rapidfuzz import fuzz

lang, note = sys.argv[1], Path(sys.argv[2])
here = Path(__file__).resolve().parent
corpus = here.parent / "corpus" if lang == "zh" else here.parents[1] / "experiments_en" / "corpus"
memos = json.loads((corpus / "memos.json").read_text(encoding="utf-8"))["memos"]
script = next(m["text"] for m in (memos if isinstance(memos, list) else [dict(id=k, **v) for k, v in memos.items()]) if m["id"] == "W01")
if lang == "zh":
    tic, terms = "就是说", ["韩昱", "蔺思远", "Koyeb", "vLLM", "Priya", "KV cache"]
    fillers = ["嗯，", "嗯", "就是说，", "就是说"]
else:
    tic, terms = "I mean", ["Jaxon", "Saoirse", "Koyeb", "vLLM", "Priya", "KV cache"]
    fillers = ["I mean, ", "I mean"]
text = note.read_text(encoding="utf-8") if note.exists() else ""
target = script
for f in fillers:
    target = target.replace(f, "")


def norm(s):
    return re.sub(r"[\W_]+", "", s.lower())


out = {
    "note_exists": note.exists(),
    "similarity_to_script_without_tics": round(fuzz.ratio(norm(target), norm(re.sub(r"^#.*$", "", text, flags=re.M))) / 100, 3),
    "tic_left": text.count(tic),
    "terms_ok": f"{sum(1 for t in terms if t in text)}/{len(terms)}",
    "terms_missing": [t for t in terms if t not in text],
}
out["pass"] = out["note_exists"] and out["tic_left"] == 0 and not out["terms_missing"] and out["similarity_to_script_without_tics"] >= 0.85
print(json.dumps(out, ensure_ascii=False, indent=1))
if "--json" in sys.argv:
    Path(sys.argv[sys.argv.index("--json") + 1]).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
