#!/usr/bin/env python3
"""Re-runs the check behind the pinyin-tone-marks dataset.

Public-corpus: the three-line tone-mark placement rule the post states is applied to
every Mandarin reading Unicode publishes in Unihan (kMandarin), and the count per rule
line, the number of syllables carrying both an a and an e, and the number of published
readings the rule contradicts are compared with dataset.json.

Quotes: every row that carries a url and a quote is re-fetched and re-read.

Exit 0 when every value recomputes and every quote is still on its page, 1 otherwise.
On a CC-CEDICT release newer than the dataset's, the entry count and export date are
reported rather than failed; every value derived from the file must still match.
--recheck re-reads everything but gives each download one minute and reports a step that
exceeds it as skipped instead of failing.
"""

import argparse
import gzip
import html
import io
import json
import re
import sys
import time
import unicodedata
import urllib.request
import zipfile
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATASET = HERE / "dataset.json"

UNIHAN_URL = "https://www.unicode.org/Public/UCD/latest/ucd/Unihan.zip"
CEDICT_URL = "https://www.mdbg.net/chinese/export/cedict/cedict_1_0_ts_utf-8_mdbg.txt.gz"
UA = "Mozilla/5.0 (compatible; article-quality-recheck; +https://www.tingyin.app)"

TONE_MARKS = {}
for _base, _seq in {
    "a": "aāáǎà",
    "e": "eēéěè",
    "i": "iīíǐì",
    "o": "oōóǒò",
    "u": "uūúǔù",
    "ü": "üǖǘǚǜ",
}.items():
    for _ch in _seq[1:]:
        TONE_MARKS[_ch] = _base

VOWELS = "aeiouü"


def fetch(url, timeout):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.read()


def norm(text):
    """Whitespace, quote style and HTML entities folded away; NFC applied."""
    text = unicodedata.normalize("NFC", text)
    text = html.unescape(text)
    text = re.sub(r"<[^>]+>", " ", text)
    text = (
        text.replace("‘", "'")
        .replace("’", "'")
        .replace("“", '"')
        .replace("”", '"')
        .replace("\u2013", "-")
        .replace("\u2014", "-")
        .replace(" ", " ")
    )
    return re.sub(r"\s+", " ", text).strip()


def page_text(raw):
    return norm(raw.decode("utf-8", errors="replace"))


def split_mark(syllable):
    """Returns (toneless syllable, positions of the tone-marked vowels)."""
    letters, positions = [], []
    for i, ch in enumerate(syllable):
        if ch in TONE_MARKS:
            letters.append(TONE_MARKS[ch])
            positions.append(i)
        else:
            letters.append(ch)
    return "".join(letters), positions


def rule_line(toneless):
    if "a" in toneless:
        return "a"
    if "e" in toneless:
        return "e"
    if "ou" in toneless:
        return "ou"
    return "last"


def measure_unihan(raw):
    archive = zipfile.ZipFile(io.BytesIO(raw))
    text = archive.read("Unihan_Readings.txt").decode("utf-8")
    version = ""
    date = ""
    readings = []
    for line in text.splitlines():
        if line.startswith("#"):
            if "Unicode Version" in line:
                version = line.split("Unicode Version")[1].strip()
            elif line.startswith("# Date:"):
                date = line.split("Date:")[1].split("[")[0].strip()
            continue
        if not line.strip():
            continue
        parts = line.split("\t")
        if len(parts) >= 3 and parts[1] == "kMandarin":
            readings.append(parts[2].strip())

    tokens = [s for r in readings for s in r.split()]
    positions = {}
    examples = {}
    deviations = []
    for token in tokens:
        toneless, at = split_mark(token)
        if len(at) != 1:
            # Neutral readings carry no mark; one reading joins two syllables.
            continue
        positions.setdefault(toneless, set()).add(at[0])
        examples.setdefault(toneless, []).append(token)

    counts = {"a": 0, "e": 0, "ou": 0, "last": 0}
    for toneless, at in positions.items():
        counts[rule_line(toneless)] += 1
        for pos in at:
            line = rule_line(toneless)
            marked = toneless[pos]
            last_vowel = max(i for i, c in enumerate(toneless) if c in VOWELS)
            agrees = (
                (line == "a" and marked == "a")
                or (line == "e" and marked == "e")
                or (line == "ou" and marked == "o")
                or (line == "last" and pos == last_vowel)
            )
            if not agrees:
                wrong = [t for t in examples[toneless] if split_mark(t)[1] == [pos]]
                deviations.append(wrong[0] if wrong else toneless)

    return {
        "unihan_version": version,
        "unihan_date": date,
        "unihan_readings": len(readings),
        "unihan_syllable_tokens": len(tokens),
        "unihan_distinct_readings": len(set(readings)),
        "syllables": len(positions),
        "rule_a_or_e": counts["a"] + counts["e"],
        "rule_a": counts["a"],
        "rule_e": counts["e"],
        "rule_ou": counts["ou"],
        "rule_last": counts["last"],
        "both_a_and_e": sum(1 for t in positions if "a" in t and "e" in t),
        "dotted_ue_after_jqxy": sum(
            1 for t in positions if len(t) > 1 and t[0] in "jqxy" and "ü" in t
        ),
        "nu_lu_both": ",".join(sorted(t for t in positions if len(t) == 2 and t[0] in "nl" and t[1] in "uü")),
        "syllables_with_v": sum(1 for t in positions if "v" in t),
        "initials_before_ue": ",".join(sorted({t[: t.index("ü")] for t in positions if "ü" in t})),
        "placement_deviations": len(deviations),
        "placement_deviation_sample": ",".join(sorted(set(deviations))),
    }


ENTRY = re.compile(r"^(\S+) (\S+) \[([^\]]+)\] (.*)$")
CONTRACTED_OF = re.compile(r"contracted variant of \S+\[[a-z0-9:]+ [a-z0-9:]+\]")


def measure_cedict(raw):
    if raw[:2] == b"\x1f\x8b":
        raw = gzip.decompress(raw)
    text = raw.decode("utf-8")
    entries = 0
    dated = ""
    both = set()
    contracted = 0
    for line in text.splitlines():
        if line.startswith("#!"):
            if "date=" in line:
                dated = line.split("date=")[1].strip()
            continue
        if not line.strip():
            continue
        match = ENTRY.match(line)
        if not match:
            continue
        entries += 1
        for token in match.group(3).split():
            toneless = re.sub(r"[0-9]", "", token).lower().replace("u:", "ü")
            if not toneless or not re.fullmatch(r"[a-zü]+", toneless):
                continue
            if "a" in toneless and "e" in toneless:
                both.add(toneless)
                if CONTRACTED_OF.search(match.group(4)):
                    contracted += 1
    return {
        "cedict_date": dated,
        "cedict_entries": entries,
        "cedict_both_a_and_e_tokens": len(both),
        "cedict_both_a_and_e_contracted": contracted,
        "cedict_both_a_and_e_names": ",".join(sorted(both)),
    }


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--recheck", action="store_true", help="re-read the pages, skip any step over a minute")
    args = parser.parse_args()
    budget = 60 if args.recheck else 300

    dataset = json.loads(DATASET.read_text(encoding="utf-8"))
    checks = dataset["results"]
    failures = []
    skipped = []

    measured = {}
    for name, url, fn in (("unihan", UNIHAN_URL, measure_unihan), ("cedict", CEDICT_URL, measure_cedict)):
        started = time.monotonic()
        try:
            measured.update(fn(fetch(url, budget)))
        except Exception as exc:  # a page or an archive that will not come back
            skipped.append(f"{name}: {type(exc).__name__}: {exc}")
        elapsed = time.monotonic() - started
        if args.recheck and elapsed > 60:
            skipped.append(f"{name}: took {elapsed:.0f}s, over the one-minute recheck budget")

    pages = {}

    def text_of(url):
        if url not in pages:
            pages[url] = page_text(fetch(url, budget))
        return pages[url]

    # CC-CEDICT is re-exported daily, so a recheck almost always reads a newer
    # release than the one measured. The post names the 25 October 2026 export and
    # never states its entry count, so on a newer release the count and the date
    # are reported, not failed; every value derived from the file still has to match.
    newer_cedict = bool(measured.get("cedict_date")) and measured.get("cedict_date") != dataset.get("corpusVersion", {}).get("cedict_date")
    release_only = {"cedict_entries"}
    notes = []

    for row in checks:
        label = row["id"]
        key = row.get("computed")
        if key:
            if key not in measured:
                skipped.append(f"{label}: value not recomputed")
            else:
                got = str(measured[key])
                if got != str(row["value"]):
                    line = f"{label}: dataset says {row['value']!r}, recomputed {got!r}"
                    (notes if newer_cedict and key in release_only else failures).append(line)
        if row.get("url") and row.get("quote"):
            try:
                haystack = text_of(row["url"])
            except Exception as exc:
                skipped.append(f"{label}: {row['url']} unavailable ({type(exc).__name__}: {exc})")
                continue
            if norm(row["quote"]) not in haystack:
                failures.append(f"{label}: quote gone from {row['url']}")

    if measured.get("unihan_version"):
        expected = dataset.get("corpusVersion", {})
        for field, key in (("unihan_version", "unihan_version"), ("unihan_date", "unihan_date"), ("cedict_date", "cedict_date")):
            if expected.get(field) and expected[field] != measured.get(key):
                line = f"corpus version: dataset says {field} {expected[field]!r}, read {measured.get(key)!r}"
                (notes if field == "cedict_date" else failures).append(line)

    for row in checks:
        print(f"  {row['id']:<34} {row.get('verdict', row.get('value', ''))}")

    if notes:
        print("\nnewer CC-CEDICT release (reported, not failed):")
        for line in notes:
            print(f"  - {line}")
    if skipped:
        print("\nnot checked:")
        for line in skipped:
            print(f"  - {line}")
    if failures:
        print("\nFAILED:")
        for line in failures:
            print(f"  - {line}")
        print(f"\n{len(failures)} failure(s)")
        return 1
    print(f"\nall {len(checks)} rows hold")
    return 0


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