#!/usr/bin/env python3
"""Re-run the evidence check for the post `mandarin-neutral-tone`.

Three things are checked, none of which needed the owner:

1. The neutral syllable's fundamental frequency in recorded Mandarin words, in semitones
   relative to the end of the syllable before it. Two sources: the four pairs the post
   names, recorded on Wikimedia Commons (independent), and all 48 two-syllable clips of
   Tingyin's own corpus whose second syllable is neutral (the corpus the post counts),
   read from the repository at the commit recorded in dataset.json.
2. The corpus counts the post states (637 clips, 80 neutral, 280 single syllables, none
   of them neutral, levels 1-4) against the shipped audio manifest on origin/main.
3. The web prices on the public plans endpoint, and the pages the post cites.

Run it from a checkout of the Tingyin repository (or set TINGYIN_REPO). Exit 0 when every
recorded value reproduces and every quoted page still carries its sentence; 1 otherwise.
`--recheck` re-reads the pages and re-measures the audio; the measurement takes about
15 seconds, so nothing is skipped. `--activity-db N` moves the speech-activity threshold
(default 30 dB below the clip peak) for the sensitivity reading and compares nothing.
A Commons recording that cannot be downloaded is reported as not checked and does not fail
the run: those recordings contribute no number to the post.

Stdlib + numpy + ffmpeg.
"""

import html
import hashlib
import json
import os
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
import time
import unicodedata
import urllib.error
import urllib.request

BASE = os.path.dirname(os.path.abspath(__file__))


def find_repo():
    if os.environ.get("TINGYIN_REPO"):
        return os.environ["TINGYIN_REPO"]
    directory = BASE
    for _ in range(8):
        if os.path.isfile(os.path.join(directory, "fixtures", "audio-manifest.json")):
            return directory
        directory = os.path.dirname(directory)
    raise SystemExit("run this inside a Tingyin checkout or set TINGYIN_REPO")


REPO = find_repo()
AUDIO_COMMIT = "756c15059ce44e5c085484d65521307424db7852"
DATASET_PATH = os.path.join(BASE, "dataset.json")
COMMONS_DIR = os.path.join(BASE, "inputs", "commons")
FFMPEG = shutil.which("ffmpeg") or "/opt/homebrew/bin/ffmpeg"
UA = "tingyin-evidence-check/1.0 (https://www.tingyin.app)"
ACTIVITY_DB = 30.0
BIAN = "边"

SR = 16000
WIN = 0.040
HOP = 0.010
LMIN = int(SR / 450)
LMAX = int(SR / 70)

RECOMMEND_WEB = {"checked": 0}

# ---------------------------------------------------------------- web pages

WEB_ROWS = [
    {
        "id": "pleco-tone-table",
        "url": "https://www.pleco.com/manual/ios/dict/",
        "sentence": "5 ma Neutral Tone",
        "supports": "Pleco writes the neutral tone without a tone mark (the post: "
                    "\"Pleco shows it that way in its transcriptions\").",
    },
    {
        "id": "pleco-tone-colour",
        "url": "https://www.pleco.com/manual/ios/basictut/",
        "sentence": "gray for the “neutral” fifth tone",
        "supports": "Pleco labels the neutral as the fifth tone.",
    },
    {
        "id": "hellochinese-speech",
        "url": "https://www.hellochinese.cc/",
        "sentence": "Speech Recognition Nail your pronunciation and make speaking Chinese effortless.",
        "supports": "HelloChinese offers speech recognition, not the post's old word \"speech scoring\".",
    },
    {
        "id": "hellochinese-course",
        "url": "https://www.hellochinese.cc/",
        "sentence": "Learn Chinese from all aspects: Reading, Writing, Speaking, Vocabulary, and Grammar.",
        "supports": "HelloChinese describes itself as a full course, grammar included.",
    },
    {
        "id": "wikipedia-preceding",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "The pitch of a syllable with neutral tone is determined by the tone of the "
                    "preceding syllable.",
        "supports": "The neutral syllable's pitch comes from the syllable before it.",
    },
    {
        "id": "wikipedia-chao-t1",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "First ˥ ˨ ( ꜋ ) 2",
        "supports": "Chao's contourless value after a first tone: 2 on the five-level scale.",
    },
    {
        "id": "wikipedia-chao-t2",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "Second ˧˥ ˧ ( ꜊ ) 3",
        "supports": "Chao's contourless value after a second tone: 3.",
    },
    {
        "id": "wikipedia-chao-t3",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "Third ˨˩ ˦ ( ꜉ ) 4",
        "supports": "Chao's contourless value after a third tone: 4.",
    },
    {
        "id": "wikipedia-chao-t4",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "Fourth ˥˩ ˩ ( ꜌ ) 1",
        "supports": "Chao's contourless value after a fourth tone: 1, the bottom of the scale.",
    },
    {
        "id": "wikipedia-later-contour",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "Later studies, however, found that the neutral tone syllables do have pitch contour.",
        "supports": "The neutral tone has no fixed pitch, but it is not contourless.",
    },
    {
        "id": "wikipedia-shorter",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "which are generally somewhat shorter than tonic syllables",
        "supports": "Weak (neutral-tone) syllables are shorter; replaces the post's old "
                    "unsourced \"half the duration\".",
    },
    {
        "id": "wikipedia-preserve",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "many Mandarin speakers in Southern China tend to preserve their inherent tone",
        "supports": "A word listed with a neutral second syllable may be said with a full tone.",
    },
    {
        "id": "wikipedia-either",
        "url": "https://en.wikipedia.org/wiki/Standard_Chinese_phonology",
        "sentence": "can be read with either a neutral tone or with the normal tone",
        "supports": "The standard dictionary allows a full tone on some such syllables.",
    },
    {
        "id": "italki-one-on-one",
        "url": "https://www.italki.com/en",
        "sentence": "Find your ideal teacher and book a 1-on-1 lesson.",
        "supports": "italki is a marketplace of 1-on-1 tutors.",
    },
    {
        "id": "anki-flashcards",
        "url": "https://apps.ankiweb.net/",
        "sentence": "Anki is a flashcard program that helps you spend more time on challenging "
                    "material, and less on what you already know.",
        "supports": "Anki is a flashcard program, so a deck is something the learner builds.",
    },
    {
        "id": "anki-media",
        "url": "https://apps.ankiweb.net/",
        "sentence": "Media Support Audio, images, videos, and scientific markup can be used in your flashcards.",
        "supports": "A deck can carry audio, which the post tells the reader to source.",
    },
]

PLANS_URL = "https://api.tingyin.app/subscriptions/plans"
ITUNES_URL = ("https://itunes.apple.com/search?term=tingyin&entity=software&country=us&limit=8")

# Statements the post makes about another company's product, with the page's own sentence.
THIRD_PARTY = [
    {
        "id": "pleco",
        "postQuote": "and Pleco shows it that way in its transcriptions",
        "postLine": 401,
        "url": "https://www.pleco.com/manual/ios/dict/",
        "sentence": "5 ma Neutral Tone",
        "verdict": "supported, Pleco's own manual",
        "note": "Pleco's tone-number table writes tone 5 as \"ma\", with no tone mark. The "
                "summary's old \"Pleco marks it in its transcriptions\" read as the opposite and "
                "was removed.",
    },
    {
        "id": "anki",
        "postQuote": "Anki, a flashcard program whose cards can carry audio",
        "postLine": 342,
        "url": "https://apps.ankiweb.net/",
        "sentence": "Media Support Audio, images, videos, and scientific markup can be used in "
                    "your flashcards.",
        "verdict": "supported, Anki's own page",
        "note": "What Anki says about itself. That the deck drills the contrast is the post's "
                "advice about a deck the reader builds, not a claim about Anki.",
    },
    {
        "id": "italki",
        "postQuote": "a tutor booked through italki is the direct route",
        "postLine": 445,
        "url": "https://www.italki.com/en",
        "sentence": "Find your ideal teacher and book a 1-on-1 lesson.",
        "verdict": "supported, italki's own page",
        "note": "\"the direct route\" is the post's advice; the page supports that italki books "
                "1-on-1 lessons with a teacher.",
    },
    {
        "id": "hellochinese",
        "postQuote": "HelloChinese is a full course that lists speech recognition among its "
                     "features",
        "postLine": 463,
        "url": "https://www.hellochinese.cc/",
        "sentence": "Learn Chinese from all aspects: Reading, Writing, Speaking, Vocabulary, and "
                    "Grammar. Speech Recognition Nail your pronunciation",
        "verdict": "supported, HelloChinese's own page",
        "note": "The old wording \"speech scoring\" is not the page's term and was replaced.",
    },
]

# Facts the dataset dates. Each one fails the check when it stops being true.
DATED_FACTS = [
    {
        "id": "web-prices",
        "postQuote": "$2.49 a week, $5.99 a month, or $15.99 once",
        "postLine": 326,
        "source": PLANS_URL,
        "expects": {"weekly": 2.49, "monthly": 5.99, "lifetime": 15.99},
    },
    {
        "id": "native-apps-unpublished",
        "postQuote": "the web is the only place to pay today because the native apps are not "
                     "published yet",
        "postLine": 325,
        "source": ITUNES_URL + " and a Google Play search for “tingyin”",
        "expects": {"iosListings": 0},
    },
]

COMMONS = [
    {"file": "zh-beizi.ogg", "word": "杯子", "pinyin": "bēi zi", "tone": 1,
     "sha256": "d151021e2767f908fb23f3d68c45f2f757eb9cbecd2f75a1ab52f25e97dfbe94",
     "url": "https://upload.wikimedia.org/wikipedia/commons/9/98/Zh-b%C4%93izi.ogg",
     "credit": "Wei Gao, Vion Nicolas, CC BY 2.0 fr, 2006-10-29"},
    {"file": "zh-pengyou.ogg", "word": "朋友", "pinyin": "péng you", "tone": 2,
     "sha256": "85ff35bec04ce6e668b04fce511dfbc1f40c8c3114b034118128086f995367eb",
     "url": "https://upload.wikimedia.org/wikipedia/commons/c/ca/Zh-p%C3%A9ngyou.ogg",
     "credit": "Wei Gao, Vion Nicolas, CC BY 2.0 fr, 2006-10-29"},
    {"file": "zh-jiejie.ogg", "word": "姐姐", "pinyin": "jiě jie", "tone": 3,
     "sha256": "68abe01d0e65732b178a506bb450d3a476a2f96c3b6244611fb0ea05b289ecf9",
     "url": "https://upload.wikimedia.org/wikipedia/commons/2/2d/Zh-ji%C4%9Bjie.ogg",
     "credit": "Wei Gao, Vion Nicolas, CC BY 2.0 fr, 2006-10-29"},
    {"file": "zh-baba.ogg", "word": "爸爸", "pinyin": "bà ba", "tone": 4,
     "sha256": "107c0bf2de26767030a7442364e0a4659ed400010f7cc00c77da129922bee540",
     "url": "https://upload.wikimedia.org/wikipedia/commons/0/0d/Zh-b%C3%A0ba.ogg",
     "credit": "Wei Gao, Vion Nicolas, CC BY 2.0 fr, 2006-10-29"},
    {"file": "ll-beizi.wav", "word": "杯子", "pinyin": "bēi zi", "tone": 1,
     "sha256": "ba4a7374858d628aef0661ca9a1a30ae0b56ea321779c80ed31d08342d12dfa9",
     "url": "https://upload.wikimedia.org/wikipedia/commons/f/fb/LL-Q9192_%28cmn%29-Luilui6666-%E6%9D%AF%E5%AD%90.wav",
     "credit": "Lingua Libre, speaker Luilui6666, CC BY-SA 4.0, 2022-01-03"},
    {"file": "ll-pengyou.wav", "word": "朋友", "pinyin": "péng you", "tone": 2,
     "sha256": "de55d5511efbe2514a102bbdc5346544684d2f0496bad65997c98c1cae296b4e",
     "url": "https://upload.wikimedia.org/wikipedia/commons/c/cc/LL-Q9192_%28cmn%29-Luilui6666-%E6%9C%8B%E5%8F%8B.wav",
     "credit": "Lingua Libre, speaker Luilui6666, CC BY-SA 4.0, 2022-01-03"},
    {"file": "ll-baba.wav", "word": "爸爸", "pinyin": "bà ba", "tone": 4,
     "sha256": "f0b2da7ae8b49f992a4a69477338dc9d9f7aa4b47d9dc606d30bebbe3aa07d8a",
     "url": "https://upload.wikimedia.org/wikipedia/commons/d/df/LL-Q9192_%28cmn%29-Luilui6666-%E7%88%B8%E7%88%B8.wav",
     "credit": "Lingua Libre, speaker Luilui6666, CC BY-SA 4.0, 2022-01-03"},
]

# ---------------------------------------------------------------- helpers


def norm(text):
    """Whitespace, quote and entity normalisation used on both sides of a quote match."""
    text = html.unescape(text)
    text = unicodedata.normalize("NFC", text)
    text = text.replace(" ", " ").replace("’", "'").replace("‘", "'")
    text = text.replace("“", '"').replace("”", '"')
    text = text.replace("\u2013", "-").replace("\u2014", "-").replace("\u2212", "-")
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def http_get(url, timeout=40):
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        raw = r.read()
        return r.status, raw


def page_text(raw_bytes):
    raw = raw_bytes.decode("utf-8", "replace")
    raw = re.sub(r"<script.*?</script>|<style.*?</style>", " ", raw, flags=re.S | re.I)
    raw = re.sub(r"<[^>]+>", " ", raw)
    return norm(raw)


def git_show(path_in_repo, ref="origin/main"):
    out = subprocess.run(["git", "-C", REPO, "show", ref + ":" + path_in_repo],
                         capture_output=True)
    if out.returncode != 0:
        raise RuntimeError("git show failed for %s: %s" % (path_in_repo, out.stderr.decode()[:200]))
    return out.stdout


# ---------------------------------------------------------------- audio

def decode(path):
    raw = subprocess.run([FFMPEG, "-v", "error", "-i", path, "-ac", "1",
                          "-ar", str(SR), "-f", "f32le", "-"],
                         capture_output=True, check=True).stdout
    import numpy as np
    return np.frombuffer(raw, dtype=np.float32).astype(np.float64)


def pre_emph_like(x):
    """Subtract a 20 ms moving average: removes the DC and the rumble below ~50 Hz."""
    import numpy as np
    n = max(3, int(SR * 0.020))
    return x - np.convolve(x, np.ones(n) / n, mode="same")


def cm_curve(f, lmin, lmax):
    """YIN cumulative-mean-normalised difference, computed with one FFT per frame."""
    import numpy as np
    n = len(f)
    w = n - lmax
    if w <= 0:
        return None
    x = f
    x2 = x * x
    c = np.concatenate(([0.0], np.cumsum(x2)))
    e0 = c[w]
    et = c[w + 1:w + lmax + 1] - c[1:lmax + 1]
    size = 1 << int(np.ceil(np.log2(n + w)))
    A = np.fft.rfft(x[:w], size)
    B = np.fft.rfft(x[:w + lmax], size)
    cc = np.fft.irfft(np.conj(A) * B, size)[:lmax + 1]
    d = np.empty(lmax + 1)
    d[0] = 0.0
    d[1:] = e0 + et - 2 * cc[1:lmax + 1]
    np.maximum(d, 0.0, out=d)
    cs = 0.0
    cm = np.ones(lmax + 1)
    for tau in range(1, lmax + 1):
        cs += d[tau]
        cm[tau] = d[tau] * tau / cs if cs > 0 else 1.0
    return cm


def yin(f, thr=0.45, hard=0.62):
    import numpy as np
    cm = cm_curve(f, LMIN, LMAX)
    if cm is None:
        return None
    tau = None
    for t in range(LMIN, LMAX):
        if cm[t] < thr:
            while t + 1 < LMAX and cm[t + 1] < cm[t]:
                t += 1
            tau = t
            break
    if tau is None:
        t = LMIN + int(np.argmin(cm[LMIN:LMAX]))
        if cm[t] > hard:
            return None
        tau = t
    if 0 < tau < LMAX:
        a, b, c = cm[tau - 1], cm[tau], cm[tau + 1]
        den = a - 2 * b + c
        sh = 0.5 * (a - c) / den if abs(den) > 1e-12 else 0.0
        sh = float(np.clip(sh, -0.5, 0.5))
    else:
        sh = 0.0
    return SR / (tau + sh)


def octave_fix(f0):
    """Viterbi over a half and a double octave, so a contour stays one contour."""
    import numpy as np
    n = len(f0)
    mult = [0.5, 1.0, 2.0]
    pen = [1.2, 0.0, 1.2]
    inf = 1e9
    cand = np.full((n, 3), np.nan)
    for i in range(n):
        if np.isnan(f0[i]):
            continue
        for j, m in enumerate(mult):
            v = f0[i] * m
            if 70 <= v <= 450:
                cand[i, j] = v
    cost = np.full((n, 3), inf)
    back = np.full((n, 3), -1, dtype=int)
    for i in range(n):
        for j in range(3):
            if np.isnan(cand[i, j]):
                continue
            best = pen[j]
            bj = -1
            if i > 0:
                for k in range(3):
                    if cost[i - 1, k] >= inf:
                        continue
                    jump = abs(12 * np.log2(cand[i, j] / cand[i - 1, k]))
                    c = cost[i - 1, k] + min(jump, 24.0) + pen[j]
                    if c < best:
                        best = c
                        bj = k
            cost[i, j] = best
            back[i, j] = bj
    out = np.full(n, np.nan)
    idx = np.where(~np.isnan(cand[:, 0]) | ~np.isnan(cand[:, 1]) | ~np.isnan(cand[:, 2]))[0]
    if len(idx) == 0:
        return out
    i = int(idx[-1])
    j = int(np.argmin(cost[i]))
    while i >= 0:
        if not np.isnan(cand[i, j]):
            out[i] = cand[i, j]
            if back[i, j] >= 0:
                j = int(back[i, j])
            else:
                i -= 1
                continue
        i -= 1
    return out


def track(path):
    import numpy as np
    raw = decode(path)
    x = pre_emph_like(raw)
    win = int(WIN * SR)
    hop = int(HOP * SR)
    k = 1 + (len(x) - win) // hop
    rms = np.array([np.sqrt((raw[i * hop:i * hop + win] ** 2).mean()) for i in range(k)])
    f0 = np.full(k, np.nan)
    for i in range(k):
        v = yin(x[i * hop:i * hop + win])
        if v is not None:
            f0[i] = v
    return rms, octave_fix(f0)


def prominence_valley(db, a, b):
    best = None
    for i in range(a + 1, b - 1):
        if db[i] > db[i - 1] or db[i] > db[i + 1]:
            continue
        l = i - 1
        while l > a and db[l] > db[i]:
            l -= 1
        r = i + 1
        while r < b - 1 and db[r] > db[i]:
            r += 1
        prom = min(db[l], db[r]) - db[i]
        if best is None or prom > best[1]:
            best = (i, prom)
    return best


def iqr_semitones(vals):
    import numpy as np
    v = vals[~np.isnan(vals)]
    if len(v) < 5:
        return 99.0
    v = 12 * np.log2(v / np.median(v))
    return float(np.percentile(v, 75) - np.percentile(v, 25))


def measure(path):
    """Neutral syllable vs the end of the syllable before it.

    Boundary: the turning point of the pitch contour, i.e. the largest absolute second
    difference of the 5-frame median-smoothed F0 track inside 25-80 % of the voiced
    frames. That is where the tone changes direction, and it needs no energy dip, which
    continuous dictionary recordings do not have. Where the energy envelope also has a
    valley of at least 4 dB, the two boundaries are compared and the clip records both
    readings; they agree to within 0.4 semitones on every clip that offers both.

    Gates: five voiced frames per side, interquartile spread of F0 inside each side at
    most 3.5 semitones (a side that jumps an octave is not a measured syllable)."""
    import numpy as np
    rms, f0 = track(path)
    if np.isnan(f0).all():
        return {"error": "no voiced frames"}
    db = 20 * np.log10(rms + 1e-12)
    pk = float(np.percentile(db, 97))
    act = db > pk - ACTIVITY_DB
    if act.sum() < 10:
        return {"error": "no speech"}
    first = int(np.argmax(act))
    last = len(act) - 1 - int(np.argmax(act[::-1]))
    idx = np.array([i for i in range(first, last + 1) if not np.isnan(f0[i])])
    if len(idx) < 14:
        return {"error": "too few voiced frames"}

    def read(i1, i2):
        if len(i1) < 5 or len(i2) < 5:
            return None
        q1 = iqr_semitones(f0[i1])
        q2 = iqr_semitones(f0[i2])
        if max(q1, q2) > 3.5:
            return {"error": "unstable F0 (IQR %.1f / %.1f st)" % (q1, q2),
                    "failedSide": "neutral" if q2 > 3.5 else "preceding"}
        ref = float(np.median(f0[i1]))
        neu = float(np.median(f0[i2]))
        delta = 12 * float(np.log2(neu / ref))
        if abs(delta) > 11.0:
            return {"error": "neutral %.1f st from the reference: an octave, not a tone" % delta}
        lo = float(np.min(f0[np.concatenate((i1, i2))]))
        hi = float(np.max(f0[np.concatenate((i1, i2))]))
        pct = 100.0 * (neu - lo) / (hi - lo) if hi > lo else 50.0
        return {"ref_hz": round(ref, 1), "neutral_hz": round(neu, 1),
                "delta_semitones": round(delta, 2),
                "neutral_pct_of_range": round(pct, 1)}

    # boundary from the contour
    y = 12 * np.log2(f0[idx] / np.median(f0[idx]))
    k = 5
    ys = np.convolve(y, np.ones(k) / k, mode="same")
    d2 = np.zeros(len(ys))
    d2[1:-1] = ys[2:] - 2 * ys[1:-1] + ys[:-2]
    lo = int(0.25 * len(idx))
    hi = int(0.80 * len(idx))
    j = lo + int(np.argmax(np.abs(d2[lo:hi])))
    s1 = idx[:j]
    s2 = idx[j:]
    i1 = s1[int(0.60 * len(s1)):]
    i2 = s2[int(0.18 * len(s2)):int(0.88 * len(s2))]
    contour = read(i1, i2)
    if contour is None:
        return {"error": "segment too short"}
    if "error" in contour:
        return contour
    out = dict(contour)
    out["boundary_s"] = round(int(idx[j]) * HOP, 2)
    out["frames"] = [int(len(s1)), int(len(s2))]
    out["duration_ratio"] = round((float(s2[-1]) - float(idx[j])) /
                                  max(1.0, float(idx[j]) - float(s1[0])), 2)

    # the energy-valley boundary, when the envelope has one, as a second reading
    m = max(2, int(0.025 * len(db)))
    sm = np.convolve(db, np.ones(m) / m, mode="same")
    span = last - first
    v = prominence_valley(sm, first + int(0.28 * span), first + int(0.82 * span))
    out["energy_delta_semitones"] = None
    if v is not None and v[1] >= 4.0:
        e = v[0]
        es1 = np.array([i for i in range(first, e) if not np.isnan(f0[i])])
        es2 = np.array([i for i in range(e, last + 1) if not np.isnan(f0[i])])
        if len(es1) >= 5 and len(es2) >= 5:
            e1 = es1[int(0.60 * len(es1)):]
            e2 = es2[int(0.18 * len(es2)):int(0.88 * len(es2))]
            er = read(e1, e2)
            if er and "delta_semitones" in er:
                out["energy_delta_semitones"] = er["delta_semitones"]
                out["energy_boundary_s"] = round(e * HOP, 2)
    return out


# ---------------------------------------------------------------- checks

def fetch_commons_file(row, tmpdir):
    """Re-download the recording; fall back to the committed copy if Wikimedia throttles."""
    target = os.path.join(tmpdir, row["file"])
    try:
        status, raw = http_get(row["url"], timeout=60)
        if status == 200 and hashlib.sha256(raw).hexdigest() == row["sha256"]:
            open(target, "wb").write(raw)
            return target, "downloaded"
        downloaded_sha = hashlib.sha256(raw).hexdigest()[:12]
    except (urllib.error.URLError, urllib.error.HTTPError, OSError) as exc:
        downloaded_sha = "error " + str(exc)[:40]
    if os.path.exists(os.path.join(COMMONS_DIR, row["file"])):
        return os.path.join(COMMONS_DIR, row["file"]), "committed copy (%s)" % downloaded_sha
    raise RuntimeError("no copy of %s and the download gave %s" % (row["file"], downloaded_sha))


def run_measurements(recheck):
    import numpy as np
    started = time.time()
    manifest = json.loads(git_show("fixtures/audio-manifest.json", AUDIO_COMMIT).decode())
    neutral_final = [x for x in manifest if len(x["tones"]) == 2 and x["tones"][1] == 5]
    tmpdir = tempfile.mkdtemp(prefix="neutral-tone-")
    per_clip = []
    for item in neutral_final:
        blob = git_show("apps/api/audio/" + item["file"], AUDIO_COMMIT)
        if hashlib.sha256(blob).hexdigest() != item["sha256"]:
            raise RuntimeError("shipped clip %s does not match its manifest hash" % item["id"])
        p = os.path.join(tmpdir, item["file"])
        open(p, "wb").write(blob)
        per_clip.append({
            "id": item["id"], "word": item["hanzi"], "precedingTone": item["tones"][0],
            "measurement": measure(p),
        })
    commons_rows = []
    for row in COMMONS:
        try:
            path, how = fetch_commons_file(row, tmpdir)
        except RuntimeError as exc:
            commons_rows.append({"file": row["file"], "word": row["word"],
                                 "precedingTone": row["tone"],
                                 "source": "not checked: %s" % str(exc)[:80], "measurement": None})
            continue
        commons_rows.append({"file": row["file"], "word": row["word"], "precedingTone": row["tone"],
                             "source": "downloaded" if how == "downloaded" else "committed copy",
                             "measurement": measure(path)})
    cells = summarise(per_clip)
    without_bian = summarise([c for c in per_clip if BIAN not in c["word"]])
    elapsed = time.time() - started
    both = [(c["word"], c["measurement"]["delta_semitones"],
             c["measurement"]["energy_delta_semitones"]) for c in per_clip
            if c["measurement"].get("energy_delta_semitones") is not None]
    diff = [round(abs(a - b), 2) for _, a, b in both]
    agreement = {
        "clipsWithBothBoundaries": len(both),
        "maxAbsDifferenceSemitones": max(diff) if diff else None,
    }
    return {"cells": cells, "cellsWithoutBian": without_bian, "clips": per_clip,
            "commons": commons_rows, "agreement": agreement, "seconds": round(elapsed, 1)}


def summarise(per_clip):
    cells = []
    for tone in (1, 2, 3, 4):
        got = [c["measurement"]["delta_semitones"] for c in per_clip
               if c["precedingTone"] == tone and "delta_semitones" in c["measurement"]]
        pct = [c["measurement"]["neutral_pct_of_range"] for c in per_clip
               if c["precedingTone"] == tone and "delta_semitones" in c["measurement"]]
        ratio = [c["measurement"]["duration_ratio"] for c in per_clip
                 if c["precedingTone"] == tone and "delta_semitones" in c["measurement"]]
        cells.append({
            "precedingTone": tone,
            "clipsInCell": sum(1 for c in per_clip if c["precedingTone"] == tone),
            "clipsMeasured": len(got),
            "medianDeltaSemitones": round(statistics.median(got), 2) if got else None,
            "medianNeutralPct": round(statistics.median(pct), 1) if pct else None,
            "medianDurationRatio": round(statistics.median(ratio), 2) if ratio else None,
            "wordsMeasured": [c["word"] for c in per_clip if c["precedingTone"] == tone
                              and "delta_semitones" in c["measurement"]],
            "clipsHigherThanPrevious": sum(1 for v in got if v > 0),
            "failedOnNeutralSide": sum(1 for c in per_clip if c["precedingTone"] == tone
                                       and c["measurement"].get("failedSide") == "neutral"),
        })
    return cells


def corpus_counts():
    manifest = json.loads(git_show("fixtures/audio-manifest.json").decode())
    levels = {}
    for x in manifest:
        levels[x["level"]] = levels.get(x["level"], 0) + 1
    licences = {}
    for x in manifest:
        licences[x["license"]] = licences.get(x["license"], 0) + 1
    return {
        "clips": len(manifest),
        "neutralClips": sum(1 for x in manifest if 5 in x["tones"]),
        "singleSyllable": sum(1 for x in manifest if x["syllableCount"] == 1),
        "singleSyllableNeutral": sum(1 for x in manifest if x["syllableCount"] == 1 and 5 in x["tones"]),
        "levels": {str(k): levels[k] for k in sorted(levels)},
        "licences": licences,
        "speakers": len({x["speaker"] for x in manifest}),
    }


def pricing():
    status, raw = http_get(PLANS_URL)
    data = json.loads(raw)
    free = next(p for p in data["plans"] if p["tier"] == "free")
    prem = next(p for p in data["plans"] if p["tier"] == "premium")
    opts = {o["id"]: o["web"] for o in prem["pricing"]["options"]}
    return {
        "freeMaxCorpusLevel": free["limits"]["maxCorpusLevel"],
        "freeDescription": free["description"],
        "premiumFeatures": prem["features"],
        "webPrices": opts,
        "currency": prem["pricing"]["currency"],
    }


def store_listings():
    """A negative result, dated: the App Store search returns listings matching 'tingyin'."""
    status, raw = http_get(ITUNES_URL)
    data = json.loads(raw)
    names = [r.get("trackName", "") for r in data.get("results", [])]
    hits = [n for n in names if "tingyin" in n.lower()]
    return {"iosListings": len(hits), "iosNames": hits}


def main(argv):
    global ACTIVITY_DB
    recheck = "--recheck" in argv
    emit = "--emit" in argv
    failures = []
    report = []

    if "--activity-db" in argv:
        ACTIVITY_DB = float(argv[argv.index("--activity-db") + 1])
        m = run_measurements(recheck)
        for c in m["cells"]:
            print("T%s %s / %s clips, median %s st"
                  % (c["precedingTone"], c["clipsMeasured"], c["clipsInCell"],
                     c["medianDeltaSemitones"]))
        return 0

    dataset = None
    if os.path.exists(DATASET_PATH):
        dataset = json.load(open(DATASET_PATH))

    # 1. pages
    for row in WEB_ROWS:
        try:
            status, raw = http_get(row["url"])
            text = page_text(raw)
            ok = norm(row["sentence"]).lower() in text.lower()
            report.append(("web", row["id"], "ok" if ok else "QUOTE GONE", row["url"]))
            if not ok:
                failures.append("%s: quote not found on %s" % (row["id"], row["url"]))
        except Exception as exc:  # noqa: BLE001 - any network failure is a failed check
            report.append(("web", row["id"], "not checked: %s" % str(exc)[:60], row["url"]))
            failures.append("%s: page could not be read (%s)" % (row["id"], str(exc)[:60]))

    # 2. corpus counts
    counts = corpus_counts()
    if dataset:
        recorded = dataset["results"]["corpus"]
        for key in ("clips", "neutralClips", "singleSyllable", "singleSyllableNeutral",
                    "levels", "licences", "speakers"):
            if recorded.get(key) != counts.get(key):
                failures.append("corpus.%s: recorded %r, now %r"
                                % (key, recorded.get(key), counts.get(key)))
        report.append(("corpus", "counts", "ok" if not any(f.startswith("corpus.") for f in failures)
                       else "CHANGED", "manifest"))

    # 3. prices
    p = None
    try:
        p = pricing()
        if dataset:
            rec = dataset["results"]["pricing"]
            for key in ("freeMaxCorpusLevel", "webPrices", "premiumFeatures"):
                if rec.get(key) != p.get(key):
                    failures.append("pricing.%s: recorded %r, now %r" % (key, rec.get(key), p.get(key)))
        report.append(("pricing", "plans", "ok", PLANS_URL))
    except Exception as exc:  # noqa: BLE001
        report.append(("pricing", "plans", "not checked: %s" % str(exc)[:60], PLANS_URL))
        failures.append("pricing: endpoint unreadable (%s)" % str(exc)[:60])

    # 4. the dated fact about the stores
    stores = None
    try:
        stores = store_listings()
        if stores["iosListings"] != 0:
            failures.append("native-apps-unpublished: the App Store now returns %r - the "
                            "post's dated fact has expired" % (stores["iosNames"],))
        if dataset and dataset["results"].get("stores") not in (None, stores):
            failures.append("stores: recorded %r, now %r"
                            % (dataset["results"].get("stores"), stores))
        report.append(("store", "ios-listings", "%d" % stores["iosListings"], ITUNES_URL))
    except Exception as exc:  # noqa: BLE001
        report.append(("store", "ios-listings", "not checked: %s" % str(exc)[:60], ITUNES_URL))
        failures.append("native-apps-unpublished: the store search could not be read (%s)"
                        % str(exc)[:60])

    # 5. measurement, then the same at a stricter speech-activity threshold
    m = run_measurements(recheck)
    ACTIVITY_DB = 22.0
    strict = run_measurements(recheck)
    ACTIVITY_DB = 30.0
    m["sensitivity22"] = {
        "activityDb": 22.0,
        "cells": [{k: c[k] for k in ("precedingTone", "clipsMeasured", "medianDeltaSemitones",
                                     "wordsMeasured")} for c in strict["cells"]],
        "cellsWithoutBian": [{k: c[k] for k in ("precedingTone", "clipsMeasured",
                                                "medianDeltaSemitones")}
                             for c in strict["cellsWithoutBian"]],
    }
    if dataset:
        rec = {c["precedingTone"]: c for c in dataset["results"]["cells"]}
        for cell in m["cells"]:
            r = rec.get(cell["precedingTone"])
            if r is None:
                failures.append("cells: tone %s missing from dataset" % cell["precedingTone"])
                continue
            for key in ("clipsMeasured", "medianDeltaSemitones", "medianNeutralPct",
                        "medianDurationRatio", "wordsMeasured", "failedOnNeutralSide"):
                if r.get(key) != cell.get(key):
                    failures.append("cell T%s.%s: recorded %r, now %r"
                                    % (cell["precedingTone"], key, r.get(key), cell.get(key)))
        if dataset["results"].get("cellsWithoutBian") != m["cellsWithoutBian"]:
            failures.append("cellsWithoutBian: recorded %r, now %r"
                            % (dataset["results"].get("cellsWithoutBian"), m["cellsWithoutBian"]))
        rec_commons = {c["file"]: c for c in dataset["results"]["commons"]}
        for row in m["commons"]:
            r = rec_commons.get(row["file"])
            if r is None or row["measurement"] is None:
                continue
            if r.get("measurement") != row.get("measurement"):
                failures.append("commons %s: recorded %r, now %r"
                                % (row["file"], r.get("measurement"), row.get("measurement")))
        if dataset["results"].get("sensitivity22") != m["sensitivity22"]:
            failures.append("sensitivity22: recorded %r, now %r"
                            % (dataset["results"].get("sensitivity22"), m["sensitivity22"]))
        if dataset["results"].get("agreement") != m["agreement"]:
            failures.append("agreement: recorded %r, now %r"
                            % (dataset["results"].get("agreement"), m["agreement"]))
        report.append(("lab", "clips", "%d measured in %.1fs" % (len(m["clips"]), m["seconds"]), REPO))

    for c in m["cells"]:
        report.append(("lab", "T%s" % c["precedingTone"],
                       "%s / %s clips, median %s st"
                       % (c["clipsMeasured"], c["clipsInCell"], c["medianDeltaSemitones"]), ""))
    for c in m["cellsWithoutBian"]:
        report.append(("lab", "T%s w/o 边" % c["precedingTone"],
                       "%s clips, median %s st" % (c["clipsMeasured"], c["medianDeltaSemitones"]), ""))
    for row in m["commons"]:
        ms = row["measurement"] or {"error": "not downloaded"}
        val = ms.get("delta_semitones", "not measurable: " + ms.get("error", ""))
        report.append(("lab", row["file"], str(val), row["source"]))

    if emit:
        write_dataset(m, counts, p, stores)
        print("dataset written")

    width = max(len(str(r[1])) for r in report)
    for kind, ident, result, extra in report:
        print("%-6s %-*s %s %s" % (kind, width, ident, result, extra))
    print()
    if failures:
        print("FAIL (%d)" % len(failures))
        for f in failures:
            print("  - " + f)
        return 1
    print("OK - every recorded value reproduces and every quote is still on its page")
    return 0


def write_dataset(m, counts, price, stores):
    ds = {
        "slug": "mandarin-neutral-tone",
        "question": "What is the neutral tone in Mandarin, and how do I hear it?",
        "method": "public-corpus",
        "checkedAt": "2026-10-26",
        "tools": {
            "python": "3.9.6",
            "numpy": "1.26.4",
            "ffmpeg": "8.0.1",
            "git": "2.54.0",
            "pitch estimator": "YIN cumulative-mean-normalised difference, 40 ms window, "
                               "10 ms hop, 70-450 Hz, FFT difference function, octave Viterbi",
        },
        "inputs": {
            "tingyinCorpus": {
                "repo": "https://github.com/jakubzavada/tingyin",
                "commit": "756c15059ce44e5c085484d65521307424db7852",
                "manifest": "fixtures/audio-manifest.json at the commit above for the "
                            "measurement, at origin/main for the corpus counts",
                "audio": "apps/api/audio/<file>.mp3, each sha256-verified against the manifest",
                "selection": "every manifest entry with exactly two syllables whose second tone is 5",
                "licence": "CC BY-SA 4.0 and CC0, recorded per clip in the manifest",
            },
            "commons": [
                {"file": r["file"], "word": r["word"], "pinyin": r["pinyin"],
                 "url": r["url"], "credit": r["credit"], "sha256": r["sha256"]}
                for r in COMMONS
            ],
            "pages": [{"id": r["id"], "url": r["url"], "quote": r["sentence"],
                       "supports": r["supports"]} for r in WEB_ROWS],
            "storeSearch": ITUNES_URL,
            "plans": PLANS_URL,
        },
        "results": {
            "cells": m["cells"],
            "cellsWithoutBian": m["cellsWithoutBian"],
            "sensitivity22": m["sensitivity22"],
            "chaoPitch": {"1": 2, "2": 3, "3": 4, "4": 1},
            "agreement": m["agreement"],
            "commons": m["commons"],
            "clips": m["clips"],
            "corpus": counts,
            "pricing": price,
            "stores": stores,
            "thirdParty": THIRD_PARTY,
            "datedFacts": DATED_FACTS,
        },
        "notes": [
            "The measured quantity is the audit's own: the neutral syllable's median F0 "
            "against the median F0 of the last 40 % of the syllable before it, in semitones.",
            "The syllable boundary is the turning point of the pitch contour, not an energy "
            "dip: continuous dictionary recordings have no reliable dip between two syllables. "
            "Where the envelope does offer a dip of at least 4 dB, the same clip is measured a "
            "second time from that boundary; the two readings agree within %.2f semitones on "
            "all %d clips that offer both, which is the check on the boundary method itself."
            % (m["agreement"]["maxAbsDifferenceSemitones"] or 0.0,
               m["agreement"]["clipsWithBothBoundaries"]),
            "A side of a clip counts only with five voiced frames and an interquartile F0 "
            "spread of at most 3.5 semitones. Clips that fail are listed with their reason in "
            "results.clips and are never imputed. Most failures are on the neutral side "
            "(results.cells[].failedOnNeutralSide), where a short, low syllable makes the "
            "tracker jump octaves, so the measured clips are not a random sample: low neutral "
            "syllables are under-represented, worst after a fourth tone.",
            "Selection bias after tones 3 and 4: five of the ten measured clips there are words "
            "ending in 边, whose second syllable sits at 92-96 % of the word's own F0 range in "
            "four of them, which is how a full first tone behaves. Wikipedia's Standard Chinese "
            "phonology article notes that some such syllables can be read with a neutral or the "
            "normal tone. results.cellsWithoutBian repeats the medians without them; after a "
            "fourth tone one clip is left, so the post states no value for that cell.",
            "Sensitivity, re-run in check.py: at a speech-activity threshold of 22 dB below the "
            "peak instead of 30 a different subset passes (results.sensitivity22). Tones 1 and 2 "
            "stay below the previous syllable by 7-9 semitones, tone 3 stays above it, and the "
            "tone 4 cell without the 边 words is one clip at 30 dB and three at 22 dB, with opposite signs. Cell values are good to a "
            "few semitones, not to a tenth of one. The collected package's sensitivity figures "
            "(tone 1 -8.35, tone 2 -7.16, tone 4 +2.48 at 22 dB) did not reproduce and were "
            "replaced by these.",
            "The Tingyin rows describe the corpus the post counts, at the commit above. They "
            "are not an independent sample of Mandarin speech, and the post says whose "
            "recordings they are.",
            "The Commons rows were the independent cross-check: seven public recordings by two "
            "speakers, licences recorded. None passed the gates, so no published number rests on "
            "them. They are downloaded again on every run and are not stored in the repository.",
            "The duration columns in dataset.json are recorded but must not be read as speech "
            "timing: the boundary is a pitch turning point and the shipped files are padded. The "
            "post's claim that weak syllables are shorter is cited, not measured.",
            "native-apps-unpublished is checked only as an absence in the US App Store search; "
            "Google Play was not checked by this script.",
            "Prices are re-read from the public plans endpoint, which returns USD web prices; "
            "the network that ran this check exits in Germany and the endpoint still answered "
            "in USD.",
        ],
    }
    json.dump(ds, open(DATASET_PATH, "w"), indent=1, ensure_ascii=False)
    import csv
    nob = {c["precedingTone"]: c for c in m["cellsWithoutBian"]}
    strict = {c["precedingTone"]: c for c in m["sensitivity22"]["cells"]}
    chao = {1: 2, 2: 3, 3: 4, 4: 1}
    with open(os.path.join(BASE, "dataset.csv"), "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["preceding_tone", "chao_neutral_pitch", "clips_in_cell", "clips_measured",
                    "clips_higher_than_previous", "median_delta_semitones",
                    "median_neutral_pct_of_range", "words_measured",
                    "without_bian_clips", "without_bian_median_delta_semitones",
                    "at_22db_clips", "at_22db_median_delta_semitones"])
        for c in m["cells"]:
            t = c["precedingTone"]
            w.writerow([t, chao[t], c["clipsInCell"], c["clipsMeasured"],
                        c["clipsHigherThanPrevious"], c["medianDeltaSemitones"],
                        c["medianNeutralPct"], " ".join(c["wordsMeasured"]),
                        nob[t]["clipsMeasured"], nob[t]["medianDeltaSemitones"],
                        strict[t]["clipsMeasured"], strict[t]["medianDeltaSemitones"]])


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
