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

Kinds of row in dataset.json:

  lab   the pitch contour of every third-tone syllable in the trainer's 637 committed
        clips, measured from the audio itself; no label is taken on trust
  code  counts read out of fixtures/audio-manifest.json, apps/api/src/corpus/
        corpus.generated.ts and apps/api/src/corpus/entitlement.ts with `git show
        origin/main:`
  page  an exact sentence on a URL, re-fetched and compared after normalisation
  absence  the App Store and Google Play have no listing for the app's bundle id

Exit 0 when every row still holds, 1 otherwise. `--recheck` re-reads the pages and runs
the same lab work: on this Mac the lab step takes about 35 s (git archive 20 s, ffmpeg
decode 4 s, pitch tracking 8 s), well under the one-minute budget, so nothing is skipped.
`--emit` rewrites dataset.json and dataset.csv from a fresh measurement.

Standard library plus numpy. ffmpeg decodes the clips.

Run it from anywhere: the repository root is found five directories above this file, so a
clone re-runs the same measurement against its own `origin/main`.
"""

import argparse
import collections
import csv
import html
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET_JSON = os.path.join(HERE, 'dataset.json')
DATASET_CSV = os.path.join(HERE, 'dataset.csv')

REPO = os.environ.get('TINGYIN_REPO') or os.path.abspath(
    os.path.join(HERE, '..', '..', '..', '..', '..'))
REF = 'origin/main'
MANIFEST_PATH = 'fixtures/audio-manifest.json'
CORPUS_PATH = 'apps/api/src/corpus/corpus.generated.ts'
ENTITLEMENT_PATH = 'apps/api/src/corpus/entitlement.ts'
AUDIO_DIRS = ('apps/web/public/audio', 'apps/api/audio')

# The corpus spans two speakers with different ranges, so every contour is expressed in
# semitones from its own speaker's median F0, never in hertz.
SR = 16000
F0_MIN, F0_MAX = 70.0, 450.0
WIN_MS, HOP_MS = 40, 10
VOICING = 0.45
N_POINTS = 20
# Inside a word the end of a syllable is the transition into the next one, so its last
# frames belong to the neighbour; a syllable that stands alone keeps its full tail.
NUC_START = 0.15
NUC_END_ALONE, NUC_END_WORD = 0.95, 0.85
# The rise of an isolated third tone sits at the very end of the syllable, so how much of
# the voiced tail a contour keeps is the one free choice that moves the headline share.
# The tighter end measures that, and L-ALONE-DIP-TIGHT publishes the difference.
NUC_END_TIGHT = 0.85
RISE_ST = 1.5          # a rise this large is a movement, not the noise on a flat tone
MIN_FRAMES = 6

TOL_ST = 0.2
TOL_HZ = 1.5
TOL_PCT = 2
TOL_COUNT = 0
CHECKED_AT = '2026-10-26'
UA = 'Mozilla/5.0'

PLANS_URL = 'https://api.tingyin.app/subscriptions/plans'
ITALKI_URL = 'https://www.italki.com/en/teachers/chinese'
PLECO_URL = 'https://www.pleco.com/manual/ios/dict/'
HC_URL = 'https://www.hellochinese.cc/'
APPSTORE_URL = 'https://itunes.apple.com/lookup?bundleId=com.tingyin.app'
PLAY_URL = 'https://play.google.com/store/apps/details?id=com.tingyin.app&hl=en&gl=US'


# ---------------------------------------------------------------- fetch and compare

def fetch(url, timeout=45):
    req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': '*/*'})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.status, r.read().decode('utf-8', errors='replace')


QUOTE_MAP = str.maketrans({'’': "'", '‘': "'", '“': '"',
                           '”': '"', '–': '-', '—': '-'})


def normalise(text):
    """Whitespace, curly quotes and HTML entities, so a quote compares as words."""
    if text is None:
        return ''
    t = re.sub(r'<(script|style)\b.*?</\1>', ' ', text, flags=re.S | re.I)
    t = re.sub(r'<[^>]+>', ' ', t)
    t = html.unescape(t)
    t = t.translate(QUOTE_MAP)
    t = t.replace(' ', ' ')
    t = re.sub(r'\s+', ' ', t)
    return t.strip()


def quote_present(page, quote):
    return normalise(quote) in normalise(page)


def git_show(path):
    return subprocess.run(['git', '-C', REPO, 'show', '%s:%s' % (REF, path)],
                          capture_output=True, check=True).stdout


def git_show_text(path):
    return git_show(path).decode('utf-8', errors='replace')


# ---------------------------------------------------------------- lab: the audio

def extract_audio(dest):
    """The 637 committed clips, out of the repository, without touching the worktree."""
    arc = subprocess.run(['git', '-C', REPO, 'archive', REF] + list(AUDIO_DIRS),
                         capture_output=True, check=True).stdout
    subprocess.run(['tar', '-x', '-C', dest], input=arc, check=True)


def clip_path(root, name):
    for d in AUDIO_DIRS:
        p = os.path.join(root, d, name)
        if os.path.exists(p):
            return p
    return None


def decode_all(root, items, temp):
    """One ffmpeg per 60 inputs, each output mapped explicitly: without -map every
    output takes the first input and 637 files decode to the same audio."""
    wav = os.path.join(temp, 'wav')
    os.makedirs(wav)
    step = 60
    for i in range(0, len(items), step):
        part = items[i:i + step]
        cmd = ['ffmpeg', '-v', 'error', '-y']
        for it in part:
            p = clip_path(root, it['file'])
            if p is None:
                raise SystemExit('missing clip %s' % it['file'])
            cmd += ['-i', p]
        for j, it in enumerate(part):
            cmd += ['-map', '%d:a' % j, '-ac', '1', '-ar', str(SR), '-f', 'wav',
                    os.path.join(wav, it['id'] + '.wav')]
        subprocess.run(cmd, check=True)
    return wav


def load(item_id, wav):
    import wave
    with wave.open(os.path.join(wav, item_id + '.wav')) as w:
        raw = np.frombuffer(w.readframes(w.getnframes()), dtype='<i2')
    return raw.astype(np.float64) / 32768.0


def f0_track(x):
    """Autocorrelation pitch per frame, with a subharmonic guard and a voicing floor."""
    win = int(SR * WIN_MS / 1000)
    hop = int(SR * HOP_MS / 1000)
    lo, hi = int(SR / F0_MAX), int(SR / F0_MIN)
    n_frames = max(0, (len(x) - win) // hop)
    nfft = 1
    while nfft < 2 * win:
        nfft *= 2
    out = np.full(n_frames, np.nan)
    for i in range(n_frames):
        fr = x[i * hop:i * hop + win].copy()
        fr -= fr.mean()
        if np.sqrt(np.mean(fr ** 2)) < 0.02:
            continue
        spec = np.fft.rfft(fr, nfft)
        ac = np.fft.irfft(spec * np.conj(spec), nfft)[:win]
        if ac[0] <= 0:
            continue
        ac = ac / ac[0]
        seg = ac[lo:hi]
        if len(seg) == 0:
            continue
        k = int(np.argmax(seg)) + lo
        if ac[k] < VOICING:
            continue
        half = k // 2
        if half >= lo:
            near = ac[half - 2:half + 3]
            k2 = int(np.argmax(near)) + half - 2
            if ac[k2] >= 0.92 * ac[k]:
                k = k2
        out[i] = SR / k
    return out


def smooth(f):
    """Median filter, then fold octave errors back onto the speaker's own range."""
    out = f.copy()
    for i in range(len(f)):
        w = f[max(0, i - 2):i + 3]
        w = w[~np.isnan(w)]
        if len(w) >= 2:
            out[i] = np.median(w)
    med = np.nanmedian(out)
    if np.isnan(med) or med <= 0:
        return out
    for i in range(len(out)):
        if np.isnan(out[i]):
            continue
        st = 12 * np.log2(out[i] / med)
        if 10 < st < 16:
            out[i] /= 2
        elif -16 < st < -10:
            out[i] *= 2
    return out


def energy(x):
    win = int(SR * WIN_MS / 1000)
    hop = int(SR * HOP_MS / 1000)
    n = max(0, (len(x) - win) // hop)
    return np.array([float(np.sqrt(np.mean(x[i * hop:i * hop + win] ** 2))) for i in range(n)])


def nucleus(seg, end_share):
    idx = np.where(~np.isnan(seg))[0]
    if len(idx) < MIN_FRAMES:
        return None
    a = int(idx[0] + NUC_START * (idx[-1] - idx[0]))
    b = int(idx[0] + end_share * (idx[-1] - idx[0]))
    v = seg[a:b + 1]
    v = v[~np.isnan(v)]
    return v if len(v) >= MIN_FRAMES else None


def contour(v, ref_hz):
    st = 12 * np.log2(v / ref_hz)
    return np.interp(np.linspace(0, len(st) - 1, N_POINTS), np.arange(len(st)), st)


def syllable_cuts(track, env, n):
    """Split a word into n syllables at the quietest point near each boundary."""
    voiced = np.where(~np.isnan(track))[0]
    if len(voiced) < 8 * n:
        return None
    a, b = voiced[0], voiced[-1]
    span = b - a
    e = np.convolve(env, np.ones(3) / 3, 'same')
    cuts = []
    for j in range(1, n):
        lo = int(a + (j - 0.22) * (span / n))
        hi = int(a + (j + 0.22) * (span / n))
        if hi <= lo:
            return None
        cuts.append(lo + int(np.argmin(e[lo:hi + 1])))
    if any(cuts[i] >= cuts[i + 1] for i in range(len(cuts) - 1)):
        return None
    return cuts


def classify(c):
    """low = never rises 1.5 st above its own minimum; dip = rises with the minimum in
    the middle; rise = rises with the minimum at the start."""
    mn = int(np.argmin(c))
    rises = float(c[-3:].mean()) - float(c[mn]) >= RISE_ST
    if not rises:
        return 'low'
    return 'dip' if 0.2 * N_POINTS <= mn <= 0.7 * N_POINTS else 'rise'


def share(seq, label):
    return 100.0 * sum(1 for s in seq if s == label) / len(seq) if seq else 0.0


def measure_lab():
    t0 = time.time()
    manifest = json.loads(git_show_text(MANIFEST_PATH))
    corpus = json.loads(corpus_items())
    cort = {x['id']: x for x in corpus}
    temp = tempfile.mkdtemp(prefix='tingyin-third-tone-')
    try:
        root = os.path.join(temp, 'src')
        os.makedirs(root)
        extract_audio(root)
        wav = decode_all(root, manifest, temp)

        track, env = {}, {}
        for it in manifest:
            x = load(it['id'], wav)
            track[it['id']] = smooth(f0_track(x))
            env[it['id']] = energy(x)

        # A speaker's reference is the median F0 of her own recordings, so a contour is
        # read against the voice that produced it.
        per = collections.defaultdict(list)
        for it in manifest:
            v = nucleus(track[it['id']], 0.95)
            if v is not None and np.median(v) > 60:
                per[it['speaker']].append(float(np.median(v)))
        ref = {k: float(np.median(v)) for k, v in per.items() if v}

        segs = {}
        for it in manifest:
            n = it['syllableCount']
            tr = track[it['id']]
            r = ref.get(it['speaker'])
            if r is None:
                continue
            if n == 1:
                v = nucleus(tr, NUC_END_ALONE)
                segs[it['id']] = [contour(v, r)] if v is not None else None
                continue
            cuts = syllable_cuts(tr, env[it['id']], n)
            if cuts is None:
                segs[it['id']] = None
                continue
            bounds = [0] + cuts + [len(tr)]
            parts = []
            for j in range(n):
                v = nucleus(tr[bounds[j]:bounds[j + 1]], NUC_END_WORD)
                if v is None:
                    parts = None
                    break
                parts.append(contour(v, r))
            segs[it['id']] = parts

        byid = {it['id']: it for it in manifest}
        alone, half, sandhi, true2, final = [], [], [], [], []
        third_measured = 0
        for it in manifest:
            s = segs.get(it['id'])
            if s is None:
                continue
            third_measured += it['tones'].count(3)
            if it['syllableCount'] == 1:
                if it['tones'][0] == 3:
                    alone.append(s[0])
                continue
            if it['syllableCount'] != 2:
                continue
            c = cort[it['id']]
            first_cite_3 = c['citationTones'][0] == 3
            is_sandhi = bool(c.get('sandhi')) and first_cite_3 and c['citationTones'] != c['tones']
            if it['tones'][0] == 3:
                half.append(s[0])
            elif is_sandhi:
                sandhi.append(s[0])
            elif it['tones'][0] == 2:
                true2.append(s[0])
            if it['tones'][1] == 3:
                final.append(s[1])

        cl = lambda g: [classify(c) for c in g]
        med = lambda g: float(np.median([float(np.median(c)) for c in g]))
        minpos = lambda g: float(np.median([float(np.argmin(c)) / (N_POINTS - 1) for c in g]))
        rng = lambda g: float(np.median([float(c.max() - c.min()) for c in g]))
        rise = lambda g: float(np.median([float(c[-3:].mean() - c.min()) for c in g]))

        alone_tight = []
        for it in manifest:
            if it['syllableCount'] != 1 or it['tones'][0] != 3:
                continue
            r = ref.get(it['speaker'])
            v = nucleus(track[it['id']], NUC_END_TIGHT)
            if r is not None and v is not None:
                alone_tight.append(contour(v, r))

        # First-position contours of all four tones, the control that says the tracker and
        # the syllable split are reading the audio rather than the labels.
        pos1 = collections.defaultdict(list)
        for it in manifest:
            s = segs.get(it['id'])
            if s and it['syllableCount'] == 2:
                pos1[it['tones'][0]].append(s[0])

        third_total = sum(it['tones'].count(3) for it in manifest)
        out = {
            'clips': len(manifest),
            'third_total': third_total,
            'third_measured': third_measured,
            'segmented': sum(1 for v in segs.values() if v),
            'alone': cl(alone), 'half': cl(half), 'sandhi': cl(sandhi),
            'true2': cl(true2), 'final': cl(final),
            'alone_tight': cl(alone_tight),
            'alone_med': med(alone), 'alone_minpos': minpos(alone), 'alone_range': rng(alone),
            'half_med': med(half), 'half_minpos': minpos(half), 'half_rise': rise(half),
            'sandhi_med': med(sandhi), 'sandhi_rise': rise(sandhi),
            'true2_med': med(true2), 'true2_rise': rise(true2),
            'pos1_n': {t: len(v) for t, v in pos1.items() if v},
            'pos1_med': {t: med(v) for t, v in pos1.items() if v},
            'pos1_range': {t: rng(v) for t, v in pos1.items() if v},
            'pos1_minpos': {t: minpos(v) for t, v in pos1.items() if v},
            'elapsed_s': round(time.time() - t0, 1),
        }
        return out
    finally:
        shutil.rmtree(temp, ignore_errors=True)


# ---------------------------------------------------------------- code: the repository

def corpus_items():
    src = git_show_text(CORPUS_PATH)
    mark = 'CORPUS_ITEMS: CorpusItem[] = '
    at = src.index(mark) + len(mark)
    start = src.index('[', at)
    depth = 0
    for i in range(start, len(src)):
        if src[i] == '[':
            depth += 1
        elif src[i] == ']':
            depth -= 1
            if depth == 0:
                return src[start:i + 1]
    raise SystemExit('corpus.generated.ts: CORPUS_ITEMS array is not closed')


def level1_sets(manifest):
    """Level 1 is the same syllable recorded in each of its tones: count the syllables, not
    the clips, so "80 clips" and "80 pairs" cannot be confused."""
    marks = str.maketrans('āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜ',
                          'aaaaeeeeiiiioooouuuuüüüü')
    sets = {}
    for x in manifest:
        if x['level'] == 1:
            sets.setdefault(x['pinyin'].translate(marks), set()).add(x['tones'][0])
    return {
        'l1_bases': len(sets),
        'l1_four': sum(1 for v in sets.values() if v == {1, 2, 3, 4}),
        'l1_pairs_23': sum(1 for v in sets.values() if {2, 3} <= v),
    }


def measure_code():
    manifest = json.loads(git_show_text(MANIFEST_PATH))
    corpus = json.loads(corpus_items())
    ent = git_show_text(ENTITLEMENT_PATH)
    single = [x for x in manifest if x['syllableCount'] == 1]
    multi = [x for x in manifest if x['syllableCount'] > 1]
    out = {
        'clips': len(manifest),
        'single': len(single),
        'level1': sum(1 for x in single if x['level'] == 1),
        'level2_single': sum(1 for x in single if x['level'] == 2),
        'multi': len(multi),
        'multi_beyond2': sum(1 for x in multi if x['level'] not in (3, 4)),
        'sandhi': sum(1 for x in corpus if x.get('sandhi')),
        'sandhi_33': sum(1 for x in corpus if x.get('sandhi')
                         and x['citationTones'] != x['tones'] and citation_has_33(x)),
        'tagged_33': sum(1 for x in manifest
                         if any(x['tones'][i] == 3 and x['tones'][i + 1] == 3
                                for i in range(len(x['tones']) - 1))),
        'public_level': int(re.search(r'PUBLIC_MAX_LEVEL = (\d+)', ent).group(1)),
        'free_level_comment': 'Level 2 is free only to a signed-in account',
        'no_session': re.search(r'if \(!user\) return \[([0-9, ]+)\]', ent).group(0),
    }
    out.update(level1_sets(manifest))
    return out


def citation_has_33(x):
    t = x['citationTones']
    return any(t[i] == 3 and t[i + 1] == 3 for i in range(len(t) - 1))


def measure_pages():
    out = {}
    status, text = fetch(PLANS_URL)
    plans = json.loads(text)
    premium = [p for p in plans['plans'] if p['tier'] == 'premium'][0]
    free = [p for p in plans['plans'] if p['tier'] == 'free'][0]
    opts = {o['id']: o for o in premium['pricing']['options']}
    out['plans_status'] = status
    out['plans_currency'] = premium['pricing']['currency']
    out['plans_weekly'] = opts['weekly']['web']
    out['plans_monthly'] = opts['monthly']['web']
    out['plans_lifetime'] = opts['lifetime']['web']
    out['plans_free'] = free['description']
    out['plans_premium'] = ('"features":{"progressSync":true,"offlineDownloads":true},'
                            '"limits":{"maxCorpusLevel":4}')
    out['plans_raw'] = text

    _, italki = fetch(ITALKI_URL)
    out['italki_page'] = italki

    _, pleco = fetch(PLECO_URL)
    out['pleco_page'] = pleco

    _, hc = fetch(HC_URL)
    out['hc_page'] = hc

    _, store = fetch(APPSTORE_URL)
    out['appstore_page'] = store

    try:
        ps, play = fetch(PLAY_URL)
    except urllib.error.HTTPError as e:
        ps, play = e.code, e.read().decode('utf-8', errors='replace')
    out['play_status'] = ps
    out['play_page'] = play
    return out


# ---------------------------------------------------------------- rows

ITALKI_QUOTE = ('Your tutor will likely provide feedback on your pronunciation and grammar '
                'to help you improve your Chinese skills.')
PLECO_QUOTE = ('So for 你好 nǐhaǒ, both syllables of which are falling-rising tones, '
               'you’d enter “ni3hao3”.')
HC_QUOTE = 'All-in-One Learning Learn Chinese from all aspects: Reading, Writing, Speaking, Vocabulary, and Grammar.'
PLAY_404 = "We're sorry, the requested URL was not found on this server."


def build_rows(lab, code, pages):
    rows = []

    def add(**kw):
        kw.setdefault('unit', '')
        kw.setdefault('tolerance', 0)
        kw.setdefault('url', '')
        kw.setdefault('source', MANIFEST_PATH)
        rows.append(kw)

    # One set per position, the same four columns for each, so the comparison table in
    # notes.md has a row of dataset.csv behind every cell.
    sets = [
        ('ALONE', lab['alone'], 'third tone, syllable said alone',
         'clips measured (the single syllables of levels 1 and 2)',
         lab['alone_med']),
        ('HALF', lab['half'], 'third tone, first syllable of a two-syllable word',
         'clips measured (before a first, second, fourth or neutral tone)',
         lab['half_med']),
        ('SANDHI', lab['sandhi'], 'first syllable written as third before another third',
         'clips measured (stored as second-then-third)', lab['sandhi_med']),
        ('FINAL', lab['final'], 'third tone, last syllable of a two-syllable word',
         'clips measured', None),
    ]
    for key, group, option, prop, median in sets:
        add(id='L-%s-N' % key, kind='lab', option=option, property=prop,
            value=len(group), unit='clips', tolerance=TOL_COUNT,
            quote='%s n=%d' % (key.lower(), len(group)))
        add(id='L-%s-LOW' % key, kind='lab', option=option,
            property='clips that never rise 1.5 semitones above their own minimum',
            value=round(share(group, 'low')), unit='% of clips', tolerance=TOL_PCT,
            quote='%s low=%d' % (key.lower(), round(share(group, 'low'))))
        add(id='L-%s-DIP' % key, kind='lab', option=option,
            property='clips that fall to a minimum in the middle and rise 1.5 semitones',
            value=round(share(group, 'dip')), unit='% of clips', tolerance=TOL_PCT,
            quote='%s dip=%d' % (key.lower(), round(share(group, 'dip'))))
        add(id='L-%s-RISE' % key, kind='lab', option=option,
            property='clips that rise 1.5 semitones with the minimum at the start',
            value=round(share(group, 'rise')), unit='% of clips', tolerance=TOL_PCT,
            quote='%s rise=%d' % (key.lower(), round(share(group, 'rise'))))
        if median is not None:
            add(id='L-%s-MED' % key, kind='lab', option=option,
                property='median pitch of the syllable',
                value=round(median, 2), unit='semitones from the speaker median',
                tolerance=TOL_ST, quote='%s median=%.2f' % (key.lower(), median))

    add(id='L-HALF-MINPOS', kind='lab', option='third tone, first syllable of a two-syllable word',
        property='position of the lowest point in the syllable',
        value=round(lab['half_minpos'], 2), unit='share of the syllable', tolerance=0.06,
        quote='half minpos=%.2f' % lab['half_minpos'])

    add(id='L-ALONE-DIP-TIGHT', kind='lab', option='third tone, syllable said alone',
        property='clips classified as a dip when the contour stops at 85% of the voiced span',
        value=round(share(lab['alone_tight'], 'dip')), unit='% of clips', tolerance=TOL_PCT,
        quote='alone tight dip=%d' % round(share(lab['alone_tight'], 'dip')))

    add(id='L-TRUE2-N', kind='lab', option='first syllable carrying a written second tone',
        property='clips measured, the control for the sandhi row',
        value=len(lab['true2']), unit='clips', tolerance=TOL_COUNT,
        quote='true2 n=%d' % len(lab['true2']))
    add(id='L-TRUE2-RISES', kind='lab', option='first syllable carrying a written second tone',
        property='clips that rise 1.5 semitones or more above their own minimum',
        value=round(share(lab['true2'], 'dip') + share(lab['true2'], 'rise')),
        unit='% of clips', tolerance=TOL_PCT,
        quote='true2 rises=%d' % round(share(lab['true2'], 'dip') + share(lab['true2'], 'rise')))
    add(id='L-TRUE2-RISE-ST', kind='lab', option='first syllable carrying a written second tone',
        property='rise from the lowest point to the end of the syllable',
        value=round(lab['true2_rise'], 2), unit='semitones', tolerance=TOL_ST,
        quote='true2 rise=%.2f' % lab['true2_rise'])
    add(id='L-HALF-RISE-ST', kind='lab', option='third tone, first syllable of a two-syllable word',
        property='rise from the lowest point to the end of the syllable',
        value=round(lab['half_rise'], 2), unit='semitones', tolerance=TOL_ST,
        quote='half rise=%.2f' % lab['half_rise'])
    add(id='L-SANDHI-RISE-ST', kind='lab',
        option='first syllable written as third before another third',
        property='rise from the lowest point to the end of the syllable',
        value=round(lab['sandhi_rise'], 2), unit='semitones', tolerance=TOL_ST,
        quote='sandhi rise=%.2f' % lab['sandhi_rise'])

    for tone, name in ((1, 'first'), (2, 'second'), (3, 'third'), (4, 'fourth')):
        if tone not in lab['pos1_med']:
            continue
        add(id='L-POS1-T%d-N' % tone, kind='lab', option='tone %d in first position' % tone,
            property='clips measured',
            value=lab['pos1_n'][tone], unit='clips', tolerance=TOL_COUNT,
            quote='pos1 tone %d n=%d' % (tone, lab['pos1_n'][tone]))
        add(id='L-POS1-T%d-MED' % tone, kind='lab', option='tone %d in first position' % tone,
            property='median pitch, the control that the split reads the audio',
            value=round(lab['pos1_med'][tone], 2), unit='semitones from the speaker median',
            tolerance=TOL_ST, quote='pos1 tone %d median=%.2f' % (tone, lab['pos1_med'][tone]))
        add(id='L-POS1-T%d-RANGE' % tone, kind='lab', option='tone %d in first position' % tone,
            property='contour range, how much the pitch moves',
            value=round(lab['pos1_range'][tone], 2), unit='semitones', tolerance=TOL_ST,
            quote='pos1 tone %d range=%.2f' % (tone, lab['pos1_range'][tone]))
        add(id='L-POS1-T%d-MINPOS' % tone, kind='lab', option='tone %d in first position' % tone,
            property='position of the lowest point, 0 at the start and 1 at the end',
            value=round(lab['pos1_minpos'][tone], 2), unit='share of the syllable',
            tolerance=0.06, quote='pos1 tone %d minpos=%.2f' % (tone, lab['pos1_minpos'][tone]))

    add(id='L-THIRD-MEASURED', kind='lab', option='all third-tone syllables',
        property='syllables measured, of the corpus total',
        value=lab['third_measured'], unit='syllables', tolerance=TOL_COUNT,
        quote='third measured=%d of %d' % (lab['third_measured'], lab['third_total']))
    add(id='L-CLIPS', kind='lab', option='all clips',
        property='clips decoded and pitch-tracked', value=lab['clips'], unit='clips',
        tolerance=TOL_COUNT, quote='clips=%d' % lab['clips'])

    # --- code rows
    add(id='C-TOTAL', kind='code', option='corpus', property='clips in the manifest',
        value=code['clips'], unit='clips', tolerance=TOL_COUNT, quote='"sha256":')
    add(id='C-SINGLE', kind='code', option='corpus', property='clips that are one syllable',
        value=code['single'], unit='clips', tolerance=TOL_COUNT, quote='"syllableCount": 1')
    add(id='C-L1', kind='code', option='level 1', property='one-syllable clips',
        value=code['level1'], unit='clips', tolerance=TOL_COUNT, quote='"level": 1')
    add(id='C-L2-SINGLE', kind='code', option='level 2', property='one-syllable clips',
        value=code['level2_single'], unit='clips', tolerance=TOL_COUNT, quote='"level": 2')
    add(id='C-L1-BASES', kind='code', option='level 1',
        property='distinct syllables recorded, each in every tone it has',
        value=code['l1_bases'], unit='syllables', tolerance=TOL_COUNT, quote='"level": 1')
    add(id='C-L1-FOUR', kind='code', option='level 1',
        property='syllables recorded in all four tones',
        value=code['l1_four'], unit='syllables', tolerance=TOL_COUNT, quote='"level": 1')
    add(id='C-L1-PAIRS23', kind='code', option='level 1',
        property='syllables with both a second-tone and a third-tone recording',
        value=code['l1_pairs_23'], unit='syllables', tolerance=TOL_COUNT, quote='"level": 1')
    add(id='C-MULTI', kind='code', option='corpus', property='clips of more than one syllable',
        value=code['multi'], unit='clips', tolerance=TOL_COUNT, quote='"syllableCount": 2')
    add(id='C-MULTI-BEYOND', kind='code', option='corpus',
        property='multi-syllable clips outside levels 3 and 4',
        value=code['multi_beyond2'], unit='clips', tolerance=TOL_COUNT,
        quote='"syllableCount": 3')
    add(id='C-SANDHI', kind='code', option='corpus',
        property='items recorded with sandhi applied, all kinds',
        value=code['sandhi'], unit='items', tolerance=TOL_COUNT, quote='"sandhi": true',
        source=CORPUS_PATH)
    add(id='C-SANDHI-33', kind='code', option='corpus',
        property='items whose written tones are third-then-third and are stored as second-then-third',
        value=code['sandhi_33'], unit='items', tolerance=TOL_COUNT, quote='"citationTones": [',
        source=CORPUS_PATH)
    add(id='C-TAGGED-33', kind='code', option='corpus',
        property='clips tagged third-then-third as spoken',
        value=code['tagged_33'], unit='clips', tolerance=TOL_COUNT, quote='"sandhi": true')
    add(id='C-PUBLIC-LEVEL', kind='code', option='access with no session',
        property='highest level served to a caller with no session',
        value=code['public_level'], unit='levels', tolerance=TOL_COUNT,
        quote='export const PUBLIC_MAX_LEVEL = %d;' % code['public_level'],
        source=ENTITLEMENT_PATH)
    add(id='C-NO-SESSION', kind='code', option='access with no session',
        property='levels a caller with no session is served', value=1, unit='levels',
        tolerance=TOL_COUNT, quote='if (!user) return [1];', source=ENTITLEMENT_PATH)

    # --- page rows
    add(id='P-PLANS-CURRENCY', kind='page', option='subscription prices',
        property='currency the plans endpoint quotes',
        value=pages['plans_currency'], quote='"currency":"%s"' % pages['plans_currency'],
        url=PLANS_URL, source='')
    add(id='P-PLANS-WEEKLY', kind='page', option='premium, web', property='weekly price',
        value=pages['plans_weekly'], unit='USD', tolerance=0.001,
        quote='"id":"weekly","kind":"recurring","web":%s' % pages['plans_weekly'],
        url=PLANS_URL, source='')
    add(id='P-PLANS-MONTHLY', kind='page', option='premium, web', property='monthly price',
        value=pages['plans_monthly'], unit='USD', tolerance=0.001,
        quote='"id":"monthly","kind":"recurring","web":%s' % pages['plans_monthly'],
        url=PLANS_URL, source='')
    add(id='P-PLANS-LIFETIME', kind='page', option='premium, web', property='one-time price',
        value=pages['plans_lifetime'], unit='USD', tolerance=0.001,
        quote='"id":"lifetime","kind":"one_time","web":%s' % pages['plans_lifetime'],
        url=PLANS_URL, source='')
    add(id='P-PLANS-FREE', kind='page', option='free tier',
        property='what the free tier includes', value=pages['plans_free'],
        quote='"tier":"free","name":"Free","description":"%s' % pages['plans_free'],
        url=PLANS_URL, source='')
    add(id='P-PLANS-PREMIUM', kind='page', option='premium',
        property='what premium adds', value='levels 3 and 4, progress sync, offline downloads',
        quote=pages['plans_premium'], url=PLANS_URL, source='')
    add(id='P-ITALKI', kind='page', option='italki', property='what a tutor does',
        value='gives feedback on pronunciation and grammar', quote=ITALKI_QUOTE,
        url=ITALKI_URL, source='')
    add(id='P-PLECO', kind='page', option='Pleco',
        property='how a word and its tone are looked up',
        value='an entry is looked up by its pinyin with tone numbers or tone-marked pinyin',
        quote=PLECO_QUOTE, url=PLECO_URL, source='')
    add(id='P-HC', kind='page', option='HelloChinese',
        property='whether the site says it teaches grammar', value='grammar is one of five named areas',
        quote=HC_QUOTE, url=HC_URL, source='')
    add(id='A-APPSTORE', kind='absence', option='iOS app',
        property='App Store listings for the bundle id com.tingyin.app', value=0,
        unit='listings', tolerance=TOL_COUNT, quote='"resultCount":0',
        url=APPSTORE_URL, source='')
    add(id='A-PLAY', kind='absence', option='Android app',
        property='Google Play listing status for com.tingyin.app', value=404,
        unit='HTTP status', tolerance=TOL_COUNT, quote=PLAY_404,
        url=PLAY_URL, source='')
    return rows


# ---------------------------------------------------------------- verification

def close(a, b, tol):
    try:
        return abs(float(a) - float(b)) <= tol + 1e-9
    except (TypeError, ValueError):
        return str(a) == str(b)


def recheck_page(row, pages):
    """Does the row's quote still appear on the page it cites?"""
    rid = row['id']
    if rid.startswith('P-PLANS'):
        return quote_present(pages['plans_raw'], row['quote'])
    if rid == 'P-ITALKI':
        return quote_present(pages['italki_page'], row['quote'])
    if rid == 'P-PLECO':
        return quote_present(pages['pleco_page'], row['quote'])
    if rid == 'P-HC':
        return quote_present(pages['hc_page'], row['quote'])
    if rid == 'A-APPSTORE':
        return quote_present(pages['appstore_page'], row['quote'])
    if rid == 'A-PLAY':
        return quote_present(pages['play_page'], row['quote']) and pages['play_status'] == 404
    return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--recheck', action='store_true',
                    help='re-read the cited pages and re-measure; the lab step is under a minute')
    ap.add_argument('--emit', action='store_true',
                    help='rewrite dataset.json and dataset.csv from a fresh measurement')
    args = ap.parse_args()

    t0 = time.time()
    lab = measure_lab()
    print('lab: %d clips, %d of %d third-tone syllables measured, %.1f s'
          % (lab['clips'], lab['third_measured'], lab['third_total'], lab['elapsed_s']))
    code = measure_code()
    pages = measure_pages()
    fresh = {(r['id']): r for r in build_rows(lab, code, pages)}

    if args.emit:
        write_dataset(list(fresh.values()), lab)
        print('wrote %s and %s' % (DATASET_JSON, DATASET_CSV))
        return 0

    with open(DATASET_JSON, encoding='utf-8') as f:
        stored = json.load(f)['results']

    failures = []
    for row in stored:
        rid = row['id']
        f = fresh.get(rid)
        if f is None:
            failures.append('%s: the script no longer produces this row' % rid)
            continue
        if row['kind'] in ('page', 'absence'):
            ok = recheck_page(row, pages)
            if ok is False:
                failures.append('%s: quote is gone from %s' % (rid, row['url']))
                continue
        if row['kind'] in ('lab', 'code', 'page', 'absence'):
            if not close(row['value'], f['value'], row.get('tolerance', 0)):
                failures.append('%s: %s is %r, dataset says %r'
                                % (rid, row['property'], f['value'], row['value']))

    for row in stored:
        if row['kind'] in ('page', 'absence') and recheck_page(row, pages) is None:
            failures.append('%s: no check is wired for this page' % row['id'])

    elapsed = time.time() - t0
    if failures:
        for msg in failures:
            print('FAIL %s' % msg)
        print('%d of %d rows failed, %.1f s' % (len(failures), len(stored), elapsed))
        return 1
    print('all %d rows hold, %.1f s' % (len(stored), elapsed))
    return 0


def write_dataset(rows, lab):
    dataset = {
        'slug': 'mandarin-third-tone',
        'method': 'lab',
        'methods': ['lab', 'code', 'page', 'absence'],
        'checkedAt': CHECKED_AT,
        'question': 'What does the Mandarin third tone actually sound like in the trainer\'s own recordings, and does the corpus labelling hold up under measurement?',
        'tools': {
            'python': '%d.%d.%d' % sys.version_info[:3],
            'numpy': np.__version__,
            'ffmpeg': subprocess.run(['ffmpeg', '-version'], capture_output=True, text=True)
            .stdout.split('\n')[0].split()[2],
        },
        'inputs': [
            {'kind': 'code', 'path': MANIFEST_PATH, 'ref': REF,
             'note': 'corpus manifest: level, tones as spoken, syllable count, speaker, licence'},
            {'kind': 'code', 'path': CORPUS_PATH, 'ref': REF,
             'note': 'the same corpus with citationTones, citationPinyin and a sandhi flag'},
            {'kind': 'code', 'path': ENTITLEMENT_PATH, 'ref': REF,
             'note': 'which levels a caller with no session is served'},
            {'kind': 'generated',
             'note': 'the 637 committed clips in apps/web/public/audio and apps/api/audio, '
                     'extracted with git archive and decoded by ffmpeg to 16 kHz mono'},
            {'kind': 'page', 'url': PLANS_URL},
            {'kind': 'page', 'url': ITALKI_URL},
            {'kind': 'page', 'url': PLECO_URL},
            {'kind': 'page', 'url': HC_URL},
            {'kind': 'page', 'url': APPSTORE_URL},
            {'kind': 'page', 'url': PLAY_URL},
        ],
        'method_note': 'Every clip is decoded and pitch-tracked (autocorrelation, 40 ms window, '
                       '10 ms hop, 70-450 Hz). A word is split into syllables at the quietest '
                       'point near each boundary; each syllable is reduced to 20 points over the '
                       'middle of its voiced span and expressed in semitones from its own '
                       'speaker\'s median F0. A syllable is "low" when it never rises 1.5 '
                       'semitones above its own minimum, "dip" when it does and its minimum is in '
                       'the middle, "rise" when it does and its minimum is at the start.',
        'results': rows,
        'notes': [
            'The lab measures 210 of the 220 third-tone syllables in the corpus. The 10 that are '
            'not measured sit in words of three or four syllables whose syllable boundaries the '
            'energy split could not place; they are excluded rather than guessed.',
            'Clips in level 1 and level 2 are single syllables by construction, so the "said '
            'alone" row is a property of the corpus, not a judgement about how the speaker '
            'phrased it.',
            'The sandhi row is stated on 18 of the 20 two-syllable items written third-then-third; '
            'the other two could not be split.',
            'How much of a syllable tail a contour keeps is the one setting that moves the '
            'isolated-syllable share: stopping at 95% of the voiced span counts the dip in the '
            'share L-ALONE-DIP reports, stopping at 85% in the share L-ALONE-DIP-TIGHT reports, '
            'because the rise an isolated third tone ends on lives in that last tenth. Every '
            'other row is unaffected, and the 18-clip sandhi row is the smallest group here, so '
            'its split between dip and plain rise should be read as approximate.',
            'Of the 55 items recorded with sandhi, 25 are third-tone sandhi (a written 3+3 stored '
            'as 2+3) and 30 are 一 or 不 changing tone in front of the syllable that follows.',
            'Prices were re-read on 2026-10-26 from the plans endpoint, which quotes '
            '"currency":"usd" and is not priced by location, so no euro price was substituted.',
            'HelloChinese: no page was found on which the company says it teaches tone sandhi as '
            'explicit grammar. The sentence recorded is the closest its site offers and does not '
            'support the post\'s claim.',
        ],
    }
    with open(DATASET_JSON, 'w', encoding='utf-8') as f:
        json.dump(dataset, f, ensure_ascii=False, indent=1)
        f.write('\n')
    cols = ['id', 'kind', 'option', 'property', 'value', 'unit', 'tolerance', 'quote', 'url', 'source']
    with open(DATASET_CSV, 'w', encoding='utf-8', newline='') as f:
        w = csv.DictWriter(f, fieldnames=cols, extrasaction='ignore')
        w.writeheader()
        for r in rows:
            w.writerow(r)


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