#!/usr/bin/env python3
"""Re-runs the check behind /blog/chinese-listening-practice-beginner.

What it checks, all against dataset.json in this folder:
  - every quoted sentence in the comparison table and in the post's statements
    about other products is still on the page it was read from,
  - the official HSK 3.0 sample archive (395 MB) still holds the level 1 paper,
    its answer key and its audio, and the level 1 paper still says what the
    table quotes; only the file list and that one PDF are read, with HTTP range
    requests,
  - the HSK syllabus PDF still yields the tone-only word sets the post counts,
  - Tingyin's corpus and its exercise code, found by walking up from this file
    (or TINGYIN_REPO), still give every count the post states.

    python3 check.py            # everything
    python3 check.py --recheck  # the same: no step here takes longer than a minute

Needs pdftotext (poppler) for the two PDFs. Exit 0 when everything holds, 1
otherwise.
"""

import argparse
import html
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unicodedata
import urllib.request
import zipfile
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, "dataset.json")
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
TIMEOUT = 60
ZIP_URL = "https://hsk-sample-1409982902.cos.ap-beijing.myqcloud.com/HSK3.0.zip"
L1_PDF = "HSK/HSK（一级）样卷.pdf"
SYLLABUS_PAGES = ("79", "90")

failures = []


def report(label, ok, detail=""):
    print("%-58s %s %s" % (label, "ok  " if ok else "FAIL", detail))
    if not ok:
        failures.append("%s %s" % (label, detail))


def normalise(text):
    text = html.unescape(text)
    for a, b in (("\u2019", "'"), ("\u2018", "'"), ("\u201c", '"'), ("\u201d", '"'),
                 ("\u2014", "-"), ("\u2013", "-"), ("\u2011", "-"), ("\u00a0", " ")):
        text = text.replace(a, b)
    return re.sub(r"\s+", " ", text).strip()


def to_text(body, content_type):
    if "json" in content_type:
        return normalise(body)
    stripped = re.sub(r"(?is)<(script|style|noscript|svg)[^>]*>.*?</\1>", " ", body)
    return normalise(re.sub(r"(?s)<[^>]+>", " ", stripped))


def get(url, headers=None, method="GET"):
    req = urllib.request.Request(url, method=method, headers=dict({"User-Agent": UA}, **(headers or {})))
    last = None
    # chinesetest.cn sometimes stalls once; a single stall is not a change on the page.
    for _ in range(3):
        try:
            with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
                return resp.status, resp.headers, resp.read()
        except Exception as exc:
            last = exc
    raise last


PAGES = {}


def page(url):
    if url not in PAGES:
        try:
            status, headers, raw = get(url)
            body = raw.decode("utf-8", "replace")
            PAGES[url] = (status, body, to_text(body, headers.get("Content-Type", "")))
        except Exception as exc:
            PAGES[url] = ("ERROR " + str(exc), "", "")
    return PAGES[url]


class HttpRange(io.RawIOBase):
    """A read-only, seekable view of a remote file, so zipfile reads only what it needs."""

    def __init__(self, url):
        self.url, self.pos = url, 0
        _, headers, _ = get(url, method="HEAD")
        self.size = int(headers["Content-Length"])

    def readable(self):
        return True

    def seekable(self):
        return True

    def tell(self):
        return self.pos

    def seek(self, offset, whence=0):
        self.pos = offset if whence == 0 else self.pos + offset if whence == 1 else self.size + offset
        return self.pos

    def readinto(self, buf):
        if self.pos >= self.size:
            return 0
        end = min(self.pos + len(buf), self.size) - 1
        _, _, data = get(self.url, headers={"Range": "bytes=%d-%d" % (self.pos, end)})
        buf[:len(data)] = data
        self.pos += len(data)
        return len(data)


def zip_name(info):
    if info.flag_bits & 0x800:
        return info.filename
    try:
        return info.filename.encode("cp437").decode("gbk")
    except UnicodeError:
        return info.filename


def pdf_text(data, args=()):
    with tempfile.NamedTemporaryFile(suffix=".pdf") as f:
        f.write(data)
        f.flush()
        out = subprocess.run(["pdftotext", *args, f.name, "-"], capture_output=True, check=True, timeout=120)
    return out.stdout.decode("utf-8", "replace")


def squash(text):
    return re.sub(r"\s+", "", text)


def check_pages(dataset):
    print("== quoted sentences ==")
    for row in dataset["results"]:
        for prop, cell in row["properties"].items():
            kind = cell.get("kind", "page")
            if kind.startswith("zip"):
                continue
            label = "%s / %s" % (row["option"], prop)
            status, body, text = page(cell["url"].split("#")[0])
            if status != 200:
                report(label, False, "fetch %s %s" % (status, cell["url"]))
                continue
            if kind == "page-prices":
                prices = sorted(float(p) for p in re.findall(r"USD (\d+\.\d\d) / trial", text))
                report(label, bool(prices), "today USD %.2f to %.2f over %d tutors (recorded: %s)" % (
                    prices[0], prices[-1], len(prices), cell["value"]) if prices else "no per-trial prices on the page")
                continue
            if not cell["quotes"]:
                report(label, len(text) > 200, "page read, nothing quoted")
                continue
            haystack = body if kind == "page-html" else text
            missing = [q for q in cell["quotes"] if normalise(q) not in normalise(haystack)]
            report(label, not missing, ("missing: %s" % missing) if missing else "")
    for claim in dataset["claims"]:
        status, body, text = page(claim["url"])
        haystack = body if claim.get("kind") == "page-html" else text
        report("claim / " + claim["post"], status == 200 and normalise(claim["quote"]) in normalise(haystack))


def check_sample_archive(dataset):
    print("\n== HSK sample archive ==")
    try:
        archive = zipfile.ZipFile(io.BufferedReader(HttpRange(ZIP_URL), buffer_size=1 << 20))
    except Exception as exc:
        report("archive readable without an account", False, str(exc))
        return
    report("archive readable without an account", True)
    names = {zip_name(i): i for i in archive.infolist()}
    for item in next(i for i in dataset["inputs"] if i.get("url") == ZIP_URL)["files"]:
        report("archive holds " + item, item in names)
    if L1_PDF not in names:
        return
    paper = squash(pdf_text(archive.read(names[L1_PDF]), ["-layout"]))
    for row in dataset["results"]:
        for prop, cell in row["properties"].items():
            if cell.get("kind") == "zip-pdf":
                for q in cell["quotes"]:
                    report("%s / %s" % (row["option"], prop), squash(q) in paper, q)
            elif cell.get("kind") == "zip-listing":
                for q in cell["quotes"]:
                    report("%s / %s" % (row["option"], prop), q in names, q)


MARKS = {"̄": 1, "́": 2, "̌": 3, "̀": 4}


def tones(pinyin):
    return tuple(MARKS[c] for c in unicodedata.normalize("NFD", pinyin) if c in MARKS)


def toneless(pinyin):
    stripped = unicodedata.normalize("NFD", pinyin)
    return re.sub(r"[\s'\u2019]", "", "".join(c for c in stripped if not unicodedata.combining(c)).lower())


def level1_rows(pdf):
    """Rows of the level 1 vocabulary table, read by position because the watermark breaks plain text."""
    bbox = pdf_text(pdf, ["-bbox", "-f", SYLLABUS_PAGES[0], "-l", SYLLABUS_PAGES[1]])
    rows = set()
    for chunk in bbox.split("<page")[1:]:
        words = [(float(a), float(b), float(c), float(d), html.unescape(t)) for a, b, c, d, t in re.findall(
            r'<word xMin="([-\d.]+)" yMin="([-\d.]+)" xMax="([-\d.]+)" yMax="([-\d.]+)">([^<]*)</word>', chunk)]
        words = [w for w in words if w[3] - w[1] < 30]  # the watermark characters are about 48 pt tall
        head = {w[4]: (w[0] + w[2]) / 2 for w in words if w[4] in ("等级", "词语", "拼音", "词性")}
        if len(head) < 4:
            continue
        split_word = (head["词语"] + head["拼音"]) / 2
        split_pos = (head["拼音"] + head["词性"]) / 2
        for w in words:
            if not re.fullmatch(r"\d+", w[4]) or w[2] > head["等级"] - 20:
                continue
            y = (w[1] + w[3]) / 2
            line = sorted(x for x in words if x is not w and abs((x[1] + x[3]) / 2 - y) < 5)
            mid = lambda x: (x[0] + x[2]) / 2
            level = "".join(x[4] for x in line if abs(mid(x) - head["等级"]) < 25)
            word = "".join(x[4] for x in line if head["等级"] + 25 < mid(x) < split_word)
            pinyin = " ".join(x[4] for x in line if split_word < mid(x) < split_pos)
            if level.startswith("1"):
                rows.add((int(w[4]), re.sub(r"\d$", "", word), pinyin))
    return sorted(rows)


def check_syllabus(dataset):
    print("\n== HSK level 1 tone-only sets ==")
    url = next(i["url"] for i in dataset["inputs"] if i.get("url", "").endswith(".pdf"))
    try:
        _, _, pdf = get(url)
    except Exception as exc:
        report("syllabus PDF", False, str(exc))
        return
    expected = dataset["hsk_tone_sets"]["verified"]
    rows = level1_rows(pdf)
    groups = defaultdict(list)
    for _, word, pinyin in rows:
        groups[toneless(pinyin)].append((word, tones(pinyin)))
    sets = {k: v for k, v in groups.items() if len({t for _, t in v}) > 1}

    def contrast(members, a, b):
        pats = {t for _, t in members}
        return any(len(x) == len(y) and sum(p != q for p, q in zip(x, y)) == 1
                   and {p for p, q in zip(x, y) if p != q} | {q for p, q in zip(x, y) if p != q} == {a, b}
                   for x in pats for y in pats if x != y)

    third_fourth = [k for k, v in sets.items() if contrast(v, 3, 4)]
    second_third = sorted(k for k, v in sets.items() if contrast(v, 2, 3))
    actual = {
        "syllabus_marked": "2026-07 实施" if "2026-07 实施" in pdf_text(pdf, ["-f", "1", "-l", "1"]) else None,
        "level_1_words": len(rows),
        "tone_only_sets": len(sets),
        "words_in_those_sets": sum(len(v) for v in sets.values()),
        "sets_contrasting_third_with_fourth": len(third_fourth),
        "of_those_in_the_na_family": sum(1 for k in third_fourth if k.startswith("na")),
        "sets_contrasting_second_with_third": len(second_third),
        "second_with_third_sets": second_third,
    }
    for key, want in expected.items():
        report(key, actual.get(key) == want, str(actual.get(key)))


def find_repo():
    candidates = [os.environ.get("TINGYIN_REPO")]
    here = HERE
    for _ in range(8):
        candidates.append(here)
        here = os.path.dirname(here)
    for root in candidates:
        if root and os.path.isfile(os.path.join(root, "fixtures", "audio-manifest.json")):
            return root
    return None


def read_repo_file(repo, rel):
    try:
        out = subprocess.run(["git", "-C", repo, "show", "origin/main:" + rel],
                             capture_output=True, check=True, timeout=60)
        return out.stdout.decode("utf-8")
    except Exception:
        with open(os.path.join(repo, rel), encoding="utf-8") as f:
            return f.read()


def check_corpus(dataset):
    print("\n== Tingyin corpus and exercise ==")
    repo = find_repo()
    if repo is None:
        report("tingyin repository", False, "not found; set TINGYIN_REPO")
        return
    manifest = json.loads(read_repo_file(repo, "fixtures/audio-manifest.json"))
    generated = read_repo_file(repo, "apps/api/src/corpus/corpus.generated.ts")
    start = generated.index("=", generated.index("CORPUS_ITEMS")) + 1
    corpus = json.loads(generated[start:generated.rindex("]") + 1])
    session = read_repo_file(repo, "apps/web/src/components/training/TrainingSession.tsx")

    def count(key):
        out = defaultdict(int)
        for item in manifest:
            out[str(item[key])] += 1
        return dict(sorted(out.items()))

    by_level = defaultdict(set)
    for item in manifest:
        by_level[str(item["level"])].add(item["syllableCount"])
    neutral = [e for e in manifest if 5 in e["tones"]]
    level1 = defaultdict(list)
    for e in manifest:
        if e["level"] == 1:
            level1[toneless(e["pinyin"])].append(e["tones"][0])
    submit = re.search(r"const submit = useCallback\(\s*\(.*?\)\s*=>\s*\{\s*setRevealed\(true\);", session, re.S)

    actual = {
        "total_clips": len(manifest),
        "clips_by_syllable_count": count("syllableCount"),
        "clips_by_level": count("level"),
        "level_1_all_single_syllable": by_level.get("1") == {1},
        "level_1_distinct_syllables": len(level1),
        "level_1_syllables_in_all_four_tones": sum(1 for v in level1.values() if sorted(v) == [1, 2, 3, 4]),
        "level_3_all_two_syllable": by_level.get("3") == {2},
        "clips_with_sandhi_applied": sum(1 for c in corpus if c.get("sandhi") is True),
        "clips_containing_a_neutral_tone": len(neutral),
        "shortest_neutral_tone_clip_in_syllables": min(e["syllableCount"] for e in neutral) if neutral else None,
        "clips_tagged_adjacent_3_then_3": sum(1 for e in manifest if any(
            a == 3 and b == 3 for a, b in zip(e["tones"], e["tones"][1:]))),
        "answer_revealed_in_submit": submit is not None,
    }
    for key, want in dataset["corpus"]["verified"].items():
        report(key, actual.get(key) == want, str(actual.get(key)))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recheck", action="store_true", help="re-read the pages; every step here is under a minute")
    ap.parse_args()
    if shutil.which("pdftotext") is None:
        print("pdftotext not found: install poppler")
        return 1
    with open(DATASET, encoding="utf-8") as f:
        dataset = json.load(f)
    check_pages(dataset)
    check_sample_archive(dataset)
    check_syllabus(dataset)
    check_corpus(dataset)
    print()
    if failures:
        print("%d failure(s)" % len(failures))
        for line in failures:
            print(" -", line)
        return 1
    print("all checks hold")
    return 0


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