# SPDX-License-Identifier: MIT
# Copyright (c) 2026 Rotem Tzemah (TaskVerdict). See LICENSE in this folder (MIT).
"""Automatic (MEASURED) checks. Each returns {"type", "pass": bool, "score": 0..1, "detail"}.
These never produce judged scores; they only fill test_outputs.metrics_json."""
import json, os, re

def _num(s):
    s = s.replace(",", "").replace("$", "").strip().rstrip(".")
    m = re.search(r"-?\d+(?:\.\d+)?", s)
    return float(m.group()) if m else None

def _norm(s): return re.sub(r"\s+", " ", s.strip().lower())

def answer_variants(text, prefix, accept, **_):
    line = next((l for l in reversed(text.splitlines()) if l.strip().lower().startswith(prefix.lower())), None)
    if line is None: return dict(pass_=False, score=0, detail="format: no '%s' line" % prefix, format_miss=True)
    ans = _norm(line[len(prefix):] if line.lower().startswith(prefix.lower()) else line)
    ok = any(re.search(r"(?<![\w])" + re.escape(_norm(a)) + r"(?![\w])", ans) for a in accept)
    return dict(pass_=ok, score=int(ok), detail=ans[:120])

def contains_any(text, any, **_):
    t = _norm(text); hit = [k for k in any if _norm(k) in t]
    return dict(pass_=bool(hit), score=int(bool(hit)), detail=hit, needs_rater=True)

def final_number(text, prefix, expected, tol=0.01, **_):
    lines = [l for l in text.splitlines() if l.strip().lower().startswith(prefix.lower())]
    if not lines: return dict(pass_=False, score=0, detail="format miss", format_miss=True)
    v = _num(lines[-1].split(":", 1)[1])
    ok = v is not None and abs(v - expected) <= tol
    return dict(pass_=ok, score=int(ok), detail=v)

def word_count_max(text, max, **_):
    n = len(re.findall(r"\S+", text)); return dict(pass_=n <= max, score=int(n <= max), detail=n)

def contains_all(text, all, **_):
    missing = [k for k in all if k.lower() not in text.lower()]
    return dict(pass_=not missing, score=(len(all) - len(missing)) / len(all), detail={"missing": missing})

def contains_min(text, min, of, **_):
    hit = [k for k in of if k.lower() in text.lower()]
    return dict(pass_=len(hit) >= min, score=int(len(hit) >= min), detail=hit)

def banned_words(text, words, **_):
    hit = [w for w in words if re.search(r"\b%s\b" % re.escape(w), text, re.I)]
    return dict(pass_=not hit, score=int(not hit), detail=hit)

def format_headline_bullets(text, headline_max_words, bullets, **_):
    lines = [l.strip() for l in text.strip().splitlines() if l.strip()]
    if not lines: return dict(pass_=False, score=0, detail="empty")
    head = re.sub(r"^[#*\s]+|[*\s]+$", "", lines[0])
    b = [l for l in lines if l.startswith("- ")]
    rest = [l for l in lines[1:] if not l.startswith("- ")]
    ok_h, ok_b, ok_c = len(head.split()) <= headline_max_words, len(b) == bullets, len(rest) >= 1
    return dict(pass_=ok_h and ok_b and ok_c, score=(ok_h + ok_b + ok_c) / 3, detail={"headline_words": len(head.split()), "bullets": len(b), "cta_lines": len(rest)})

def keyed_lines(text, expected, tol=0.01, **_):
    got = {}
    for l in text.splitlines():
        m = re.match(r"\s*\**\s*([QA]\d+)\s*\**\s*[:.)-]\s*(.+)", l)
        if m: got[m.group(1).upper()] = m.group(2).strip().strip("*").strip()
    per = {}
    for k, v in expected.items():
        g = got.get(k)
        if g is None: per[k] = False
        elif isinstance(v, (int, float)): n = _num(g); per[k] = n is not None and abs(n - v) <= tol
        else: per[k] = _norm(str(v)) in _norm(g)
    return dict(pass_=all(per.values()), score=sum(per.values()) / len(per), detail=per)

def json_fields(text, expected, **_):
    raw = text.strip()
    try: obj = json.loads(raw); repaired = False
    except Exception:
        m = re.search(r"\{.*\}", raw, re.S); repaired = True
        try: obj = json.loads(m.group()) if m else None
        except Exception: obj = None
    if not isinstance(obj, dict): return dict(pass_=False, score=0, detail="invalid JSON")
    def eq(a, b):
        if isinstance(b, list): return isinstance(a, list) and [re.sub(r"^the ", "", _norm(str(x))) for x in a] == [re.sub(r"^the ", "", _norm(x)) for x in b]
        if isinstance(b, int): return a == b and not isinstance(a, bool)
        return isinstance(a, str) and _norm(a) == _norm(b)
    fields = {k: eq(obj.get(k), v) for k, v in expected.items()}
    keys_exact = set(obj) == set(expected)
    score = sum(fields.values()) / len(fields)
    return dict(pass_=keys_exact and all(fields.values()) and not repaired, score=score, detail={"fields": fields, "keys_exact": keys_exact, "needed_repair": repaired})

def hebrew_ratio_min(text, min, **_):
    letters = re.findall(r"[^\W\d_]", text)
    heb = [c for c in letters if "\u0590" <= c <= "\u05FF"]
    r = len(heb) / len(letters) if letters else 0
    return dict(pass_=r >= min, score=int(r >= min), detail=round(r, 3))

def ocr_strings(text, strings, **_):
    return dict(pass_=None, score=None, detail="deferred: run OCR on the image file offline", deferred=True)


# ---------------- v0.2 additions (2026-10-09, lab3: writing + coding protocols). Additive only; older checks unchanged.
def regex_all(text, patterns, **_):
    missing = [p for p in patterns if not re.search(p, text or "", re.I)]
    return dict(pass_=not missing, score=(len(patterns) - len(missing)) / len(patterns), detail={"missing": missing})

def forbidden_chars(text, chars, **_):
    hit = sorted({c for c in chars if c in (text or "")})
    return dict(pass_=not hit, score=int(not hit), detail=hit)

def paragraph_count(text, n, **_):
    paras = [p for p in re.split(r"\n\s*\n", (text or "").strip()) if p.strip()]
    return dict(pass_=len(paras) == n, score=int(len(paras) == n), detail=len(paras))

def _syllables(w):
    w = re.sub(r"[^a-z]", "", w.lower())
    if not w: return 0
    groups = re.findall(r"[aeiouy]+", w)
    n = len(groups) - (1 if w.endswith("e") and not w.endswith(("le", "ee")) and len(groups) > 1 else 0)
    return max(1, n)

def fk_grade(text):
    """Flesch-Kincaid grade level (standard formula, simple vowel-group syllable counter). Deterministic; documented in lab/protocols/writing.md."""
    sents = [s for s in re.split(r"[.!?]+(?:\s|$)", text or "") if re.search(r"[A-Za-z]", s)]
    words = re.findall(r"[A-Za-z][A-Za-z'-]*", text or "")
    if not sents or not words: return None
    syl = sum(_syllables(w) for w in words)
    return 0.39 * len(words) / len(sents) + 11.8 * syl / len(words) - 15.59

def fk_grade_max(text, max, **_):
    g = fk_grade(text)
    ok = g is not None and g <= max
    return dict(pass_=ok, score=int(ok), detail=None if g is None else round(g, 2))

def numbered_lines(text, n, max_chars, **_):
    lines = [l.strip() for l in (text or "").strip().splitlines() if l.strip()]
    items = [re.sub(r"^\**\s*\d+[.)]\s*", "", l).strip().strip("*").strip() for l in lines if re.match(r"^\**\s*\d+[.)]", l)]
    long_ = [i for i in items if len(i.strip('"')) > max_chars]
    ok_n, ok_len, ok_only = len(items) == n, not long_, len(items) == len(lines)
    return dict(pass_=ok_n and ok_len and ok_only, score=(ok_n + ok_len + ok_only) / 3,
                detail={"items": len(items), "over_limit": len(long_), "extra_lines": len(lines) - len(items)})

def extract_code(text, langs):
    """First fenced block whose tag is in langs; else first fenced block; else the whole text."""
    blocks = re.findall(r"```([A-Za-z0-9_+-]*)[ \t]*\n(.*?)```", text or "", re.S)
    for tag, body in blocks:
        if tag.lower() in langs: return body, "fenced:" + tag.lower()
    if blocks: return blocks[0][1], "fenced:other"
    m = re.search(r"```([A-Za-z0-9_+-]*)[ \t]*\n(.*)$", text or "", re.S)  # opening fence never closed (output ended)
    if m: return m.group(2), "fenced_unclosed:" + (m.group(1).lower() or "none")
    return text or "", "unfenced"

def _sandbox_run(cmd, cwd, timeout):
    import resource, subprocess
    def lim():
        resource.setrlimit(resource.RLIMIT_CPU, (timeout, timeout))
        resource.setrlimit(resource.RLIMIT_AS, (1 << 30, 1 << 30))
        os.setsid()
    env = {"PATH": "/usr/bin:/bin", "HOME": cwd, "LANG": "C.UTF-8"}
    try:
        p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout + 5, preexec_fn=lim, env=env)
        return p.returncode, p.stdout[-4000:], p.stderr[-2000:]
    except subprocess.TimeoutExpired:
        return None, "", "timeout"

def code_tests(text, lang, tests_file, timeout=20, **_):
    """Run a HIDDEN test file (never shown to the model) against the extracted solution in a temp dir with CPU/memory limits.
    The test file prints one JSON line {"passed": int, "total": int, "failures": [...]}. Score = passed/total; pass = all passed."""
    import tempfile, shutil
    from pathlib import Path
    here = Path(__file__).resolve().parent
    langs = {"python": ("python", "py", "python3"), "javascript": ("javascript", "js", "node"), "sql": ("sql", "sqlite")}[lang]
    code, how = extract_code(text, langs)
    tf = here / "suites" / tests_file
    with tempfile.TemporaryDirectory() as d:
        sol = {"python": "solution.py", "javascript": "solution.js", "sql": "solution.sql"}[lang]
        Path(d, sol).write_text(code)
        dst = Path(d, tf.name); shutil.copy(tf, dst)
        cmd = ["node", dst.name] if tf.suffix == ".js" else ["python3", "-E", "-s", dst.name]
        rc, out, err = _sandbox_run(cmd, d, timeout)
    res = None
    for line in reversed(out.splitlines()):
        try: res = json.loads(line); break
        except Exception: continue
    if not isinstance(res, dict) or "total" not in res:
        return dict(pass_=False, score=0, detail={"extraction": how, "error": (err or out)[-300:] or "no result line", "rc": rc})
    sc = res["passed"] / res["total"] if res["total"] else 0
    return dict(pass_=res["passed"] == res["total"], score=sc,
                detail={"extraction": how, "passed": res["passed"], "total": res["total"], "failures": res.get("failures", [])[:5]})

CHECKS = {f.__name__: f for f in [answer_variants, contains_any, final_number, word_count_max, contains_all, contains_min, banned_words,
                                  format_headline_bullets, keyed_lines, json_fields, hebrew_ratio_min, ocr_strings,
                                  regex_all, forbidden_chars, paragraph_count, fk_grade_max, numbered_lines, code_tests]}

def run_checks(text, checks):
    out = []
    for c in checks:
        args = {k: v for k, v in c.items() if k not in ("type", "note")}
        r = CHECKS[c["type"]](text or "", **args)
        r["pass"] = r.pop("pass_"); r["type"] = c["type"]; out.append(r)
    scored = [r["score"] for r in out if r.get("score") is not None]
    return out, (sum(scored) / len(scored) if scored else None)

def wer(ref, hyp):
    """Word error rate (lower-cased, punctuation stripped) - used by transcription/voice suites."""
    norm = lambda s: re.sub(r"[^\w\s']", " ", s.lower()).split()
    r, h = norm(ref), norm(hyp)
    d = list(range(len(h) + 1))
    for i in range(1, len(r) + 1):
        prev, d[0] = d[0], i
        for j in range(1, len(h) + 1):
            cur = min(d[j] + 1, d[j - 1] + 1, prev + (r[i - 1] != h[j - 1])); prev, d[j] = d[j], cur
    return d[len(h)] / max(1, len(r))

# ---------------------------------------------------------------------------------------------------------------
# Whisper-style text normalisation + detailed WER (added 2026-10-08 for Lab run #1, STT-01-TTS).
# Uses OpenAI Whisper's EnglishTextNormalizer (MIT; packaged as `whisper-normalizer` on PyPI) when installed:
# lower-case, strip bracketed/filler tokens, standardise numbers ("twenty-six hundred" -> 2600, "$79"), British ->
# American spelling, remove punctuation. The SAME normaliser is applied to the reference and to every hypothesis.
# Fallback (if the package is missing) is a simpler normaliser; the result records which one was used.
def whisper_normalize(text):
    try:
        from whisper_normalizer.english import EnglishTextNormalizer
        global _WN
        try: _WN
        except NameError: _WN = EnglishTextNormalizer()
        return _WN(text), "whisper_normalizer.EnglishTextNormalizer"
    except ImportError:
        t = text.lower()
        t = re.sub(r"[\[\(<][^\]\)>]*[\]\)>]", " ", t)
        t = re.sub(r"\b(uh|um|hmm|mm|mhm|ah|oh)\b", " ", t)
        t = re.sub(r"[^\w\s'.$%]", " ", t); t = re.sub(r"(?<!\d)\.|\.(?!\d)", " ", t)
        return re.sub(r"\s+", " ", t).strip(), "fallback_basic"

def align_words(r, h):
    """Levenshtein alignment on word lists. Returns (S, D, I, ops) with ops = [(op, ref_idx, hyp_idx)], op in =,S,D,I."""
    n, m = len(r), len(h)
    D = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1): D[i][0] = i
    for j in range(1, m + 1): D[0][j] = j
    for i in range(1, n + 1):
        ri = r[i - 1]; Di, Dp = D[i], D[i - 1]
        for j in range(1, m + 1):
            Di[j] = min(Dp[j] + 1, Di[j - 1] + 1, Dp[j - 1] + (ri != h[j - 1]))
    i, j, ops = n, m, []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and D[i][j] == D[i - 1][j - 1] + (r[i - 1] != h[j - 1]):
            ops.append(("=" if r[i - 1] == h[j - 1] else "S", i - 1, j - 1)); i, j = i - 1, j - 1
        elif i > 0 and D[i][j] == D[i - 1][j] + 1: ops.append(("D", i - 1, None)); i -= 1
        else: ops.append(("I", None, j - 1)); j -= 1
    ops.reverse()
    c = {k: sum(1 for o in ops if o[0] == k) for k in "SDI="}
    return c["S"], c["D"], c["I"], ops

def wer_whisper(ref, hyp):
    """WER after Whisper-style normalisation of both sides. Returns dict(wer, S, D, I, N, hits, normaliser)."""
    rn, name = whisper_normalize(ref); hn, _ = whisper_normalize(hyp)
    r, h = rn.split(), hn.split()
    S, Dl, I, _ = align_words(r, h)
    return dict(wer=round((S + Dl + I) / max(1, len(r)), 5), S=S, D=Dl, I=I, N=len(r), hits=len(r) - S - Dl, normaliser=name)
