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

Kinds of row in dataset.json:

  lab     the pitch contours of the trainer's own free-level clips, re-measured from
          the clips committed in the product repository
  code    counts read out of fixtures/audio-manifest.json and one sentence of
          apps/api/src/corpus/entitlement.ts, both read 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
  product counts from the production database, read once with query.js; production is
          out of reach here, so only the stored output's internal consistency and its
          suppression of every cell under 10 accounts are re-checked

Exit 0 when every row still holds, 1 otherwise. `--recheck` runs the same work and is
accepted for the weekly recheck: the only lab step here takes about 20 s on this Mac,
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 and ffprobe decode the clips.
"""

import argparse
import csv
import html
import itertools
import json
import os
import re
import subprocess
import sys
import time
import unicodedata
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 = subprocess.run(['git', '-C', os.path.dirname(os.path.abspath(__file__)), 'rev-parse',
                       '--show-toplevel'], capture_output=True, text=True).stdout.strip()
REF = 'origin/main'
AUDIO_DIR = 'apps/web/public/audio'
MANIFEST_PATH = 'fixtures/audio-manifest.json'
ENTITLEMENT_PATH = 'apps/api/src/corpus/entitlement.ts'

SR = 16000             # analysis sample rate
F0_MIN, F0_MAX = 70.0, 450.0
WIN_MS, HOP_MS = 40, 10
VOICING = 0.45
N_POINTS = 20          # contour resampled to this many points across the nucleus
NUC_START, NUC_END = 0.15, 0.95   # nucleus as a share of the voiced span

# Tolerances: a different numpy or ffmpeg build moves the last decimal, not the reading.
TOL_ST = 0.15          # semitones
TOL_HZ = 1.5
TOL_SHARE = 0.02
TOL_COUNT = 0
TOL_PCT = 2
MIN_USERS = 10
SUPPRESSED = 'suppressed (<10)'

CHECKED_AT = '2026-10-26'
UA = 'Mozilla/5.0'


# ---------------------------------------------------------------- fetch helpers

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


def page_text(url):
    status, text = fetch(url)
    if 'api.openalex.org' in url:
        inv = json.loads(text).get('abstract_inverted_index') or {}
        words = {p: w for w, ps in inv.items() for p in ps}
        text = ' '.join(words[i] for i in sorted(words))
    return status, text


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


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


QUOTE_MAP = str.maketrans({'’': "'", '‘': "'", '“': '"',
                           '”': '"', '\u2013': '-', '\u2014': '-'})


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_text, quote):
    return normalise(quote) in normalise(page_text)


# ---------------------------------------------------------------- lab: F0 contours

def decode_wav_bytes(data, sr=SR):
    p = subprocess.run(['ffmpeg', '-v', 'error', '-i', 'pipe:0',
                        '-f', 'f32le', '-ac', '1', '-ar', str(sr), '-'],
                       input=data, capture_output=True, check=True)
    return np.frombuffer(p.stdout, dtype='<f4').astype(np.float64)


def f0_track(x, sr=SR):
    """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)
    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
        n = 1
        while n < 2 * len(fr):
            n *= 2
        spec = np.fft.rfft(fr, n)
        ac = np.fft.irfft(spec * np.conj(spec), n)[:len(fr)]
        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
        if 1 <= k < len(ac) - 1:
            a, b, c = ac[k - 1], ac[k], ac[k + 1]
            den = a - 2 * b + c
            d = 0.5 * (a - c) / den if den != 0 else 0.0
        else:
            d = 0.0
        out[i] = sr / (k + d)
    return out


def smooth(f):
    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)
    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 nucleus(f):
    idx = np.where(~np.isnan(f))[0]
    if len(idx) < 10:
        return None
    a = int(idx[0] + NUC_START * (idx[-1] - idx[0]))
    b = int(idx[0] + NUC_END * (idx[-1] - idx[0]))
    seg = f[a:b + 1]
    seg = seg[~np.isnan(seg)]
    if len(seg) < 8:
        return None
    return seg


def resample(seg, n=N_POINTS):
    pos = np.linspace(0, len(seg) - 1, n)
    return np.interp(pos, np.arange(len(seg)), seg)


def measure_lab():
    """Decode every free-level clip, track its pitch, and summarise the four tones."""
    t0 = time.time()
    manifest = json.loads(git_show_text(MANIFEST_PATH))
    items = [x for x in manifest if x['level'] in (1, 2)]
    tracks = []
    for it in items:
        data = git_show('%s/%s' % (AUDIO_DIR, it['file'])).stdout
        seg = nucleus(smooth(f0_track(decode_wav_bytes(data))))
        if seg is not None:
            tracks.append((it, seg))

    refs = {}
    for spk in {t[0]['speaker'] for t in tracks}:
        pooled = np.concatenate([t[1] for t in tracks if t[0]['speaker'] == spk])
        refs[spk] = float(np.median(pooled))

    clips = []
    for it, seg in tracks:
        st = 12 * np.log2(seg / refs[it['speaker']])
        clips.append({'id': it['id'], 'tone': it['tones'][0], 'level': it['level'],
                      'speaker': it['speaker'], 'median_hz': float(np.median(seg)),
                      'contour': resample(st)})

    tones = {}
    for tone in (1, 2, 3, 4):
        sub = [c for c in clips if c['tone'] == tone]
        M = np.array([c['contour'] for c in sub])
        mean = M.mean(axis=0)
        slope = float(np.polyfit(np.linspace(0, 1, M.shape[1]), mean, 1)[0])
        dips = []
        for row in M:
            mn = int(np.argmin(row))
            mid = 0.2 * len(row) <= mn <= 0.7 * len(row)
            rises = row[-1] - row[mn] >= 1.5
            dips.append(1 if (mid and rises) else 0)
        tones[tone] = {
            'n': len(sub),
            'median_hz': float(np.median([c['median_hz'] for c in sub])),
            'mean_contour': [float(v) for v in mean],
            'start_st': float(mean[:2].mean()),
            'end_st': float(mean[-2:].mean()),
            'slope_st': slope,
            'min_pos': int(np.argmin(mean)) / (len(mean) - 1),
            'range_st': float(mean.max() - mean.min()),
            'dip_share': sum(dips) / len(dips),
        }

    pairs, shape_pairs = [], []
    for a, b in itertools.combinations((1, 2, 3, 4), 2):
        ca = np.array(tones[a]['mean_contour'])
        cb = np.array(tones[b]['mean_contour'])
        pairs.append({'pair': '%d-%d' % (a, b),
                      'rms_st': float(np.sqrt(np.mean((ca - cb) ** 2)))})
        sa, sb = ca - ca.mean(), cb - cb.mean()
        shape_pairs.append({'pair': '%d-%d' % (a, b),
                            'rms_st': float(np.sqrt(np.mean((sa - sb) ** 2)))})
    pairs.sort(key=lambda p: p['rms_st'])
    shape_pairs.sort(key=lambda p: p['rms_st'])

    return {
        'clips_measured': len(clips),
        'reference_hz': refs,
        'tones': tones,
        'pairs_full': pairs,
        'pairs_shape': shape_pairs,
        'elapsed_s': round(time.time() - t0, 1),
    }


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

def build_rows(lab):
    rows = []

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

    # --- lab rows: one per tone, plus the pair ordering
    t = lab['tones']
    for tone in (1, 2, 3, 4):
        a = t[tone]
        add(id='L-T%d-N' % tone, kind='lab', option='tone %d' % tone,
            property='clips measured', value=a['n'], unit='clips', tolerance=TOL_COUNT,
            quote='tone %d: n=%d' % (tone, a['n']), url='', source=MANIFEST_PATH)
        add(id='L-T%d-HZ' % tone, kind='lab', option='tone %d' % tone,
            property='median F0', value=round(a['median_hz'], 1), unit='Hz',
            tolerance=TOL_HZ,
            quote='tone %d: median_hz=%.1f' % (tone, a['median_hz']),
            url='', source=MANIFEST_PATH)
        add(id='L-T%d-START' % tone, kind='lab', option='tone %d' % tone,
            property='contour at the start of the nucleus', value=round(a['start_st'], 2),
            unit='semitones from the speaker reference', tolerance=TOL_ST,
            quote='tone %d: start_st=%.2f' % (tone, a['start_st']),
            url='', source=MANIFEST_PATH)
        add(id='L-T%d-END' % tone, kind='lab', option='tone %d' % tone,
            property='contour at the end of the nucleus', value=round(a['end_st'], 2),
            unit='semitones from the speaker reference', tolerance=TOL_ST,
            quote='tone %d: end_st=%.2f' % (tone, a['end_st']),
            url='', source=MANIFEST_PATH)
        add(id='L-T%d-SLOPE' % tone, kind='lab', option='tone %d' % tone,
            property='contour slope across the nucleus', value=round(a['slope_st'], 2),
            unit='semitones per nucleus', tolerance=TOL_ST,
            quote='tone %d: slope_st=%.2f' % (tone, a['slope_st']),
            url='', source=MANIFEST_PATH)
        add(id='L-T%d-RANGE' % tone, kind='lab', option='tone %d' % tone,
            property='contour range', value=round(a['range_st'], 2), unit='semitones',
            tolerance=TOL_ST,
            quote='tone %d: range_st=%.2f' % (tone, a['range_st']),
            url='', source=MANIFEST_PATH)
    for tone in (1, 2, 3, 4):
        add(id='L-T%d-DIP' % tone, kind='lab', option='tone %d' % tone,
            property='clips that dip and then rise at least 1.5 semitones',
            value=round(t[tone]['dip_share'] * 100), unit='% of clips', tolerance=TOL_PCT,
            quote='tone %d: dip_pct=%d' % (tone, round(t[tone]['dip_share'] * 100)), url='',
            source=MANIFEST_PATH)
    add(id='L-T3-MINPOS', kind='lab', option='tone 3',
        property='position of the lowest point in the nucleus',
        value=round(t[3]['min_pos'], 2), unit='share of the nucleus', tolerance=TOL_SHARE,
        quote='tone 3: min_pos=%.2f' % t[3]['min_pos'], url='', source=MANIFEST_PATH)

    for i, p in enumerate(lab['pairs_full'], 1):
        add(id='L-PAIR-FULL-%d' % i, kind='lab',
            option='pair %s' % p['pair'],
            property='rank of the pair by full-contour distance (%d of 6, closest first)' % i,
            value=round(p['rms_st'], 2), unit='semitones RMS', tolerance=TOL_ST,
            quote='full contour: %s %.2f' % (p['pair'], p['rms_st']),
            url='', source=MANIFEST_PATH)
    for i, p in enumerate(lab['pairs_shape'], 1):
        add(id='L-PAIR-SHAPE-%d' % i, kind='lab',
            option='pair %s' % p['pair'],
            property='rank of the pair by shape-only distance (%d of 6, closest first)' % i,
            value=round(p['rms_st'], 2), unit='semitones RMS', tolerance=TOL_ST,
            quote='shape only: %s %.2f' % (p['pair'], p['rms_st']),
            url='', source=MANIFEST_PATH)

    # --- code rows: the product's own corpus and access rules
    add(id='C-L1-COUNT', kind='code', option='level 1',
        property='items in the corpus manifest', value=len(_l1()), unit='items',
        tolerance=TOL_COUNT,
        quote='"level": 1', url='', source=MANIFEST_PATH)
    add(id='C-L1-SYLL', kind='code', option='level 1',
        property='items that are one syllable',
        value=sum(1 for x in _l1() if x['syllableCount'] == 1), unit='items',
        tolerance=TOL_COUNT, quote='"syllableCount": 1', url='', source=MANIFEST_PATH)
    add(id='C-L1-BASES', kind='code', option='level 1',
        property='syllables that appear in all four tones',
        value=_l1_bases(), unit='syllables', tolerance=TOL_COUNT,
        quote='"pinyin": "bà"', url='', source=MANIFEST_PATH)
    add(id='C-L2-COUNT', kind='code', option='level 2',
        property='items in the corpus manifest', value=len(_l2()), unit='items',
        tolerance=TOL_COUNT, quote='"level": 2', url='', source=MANIFEST_PATH)
    add(id='C-TOTAL', kind='code', option='all levels',
        property='clips in the corpus manifest', value=len(_manifest()), unit='clips',
        tolerance=TOL_COUNT, quote='"sha256"', url='', source=MANIFEST_PATH)
    add(id='C-CC-BY-SA', kind='code', option='all levels',
        property='clips licensed CC BY-SA 4.0',
        value=sum(1 for x in _manifest() if x['license'] == 'CC BY-SA 4.0'), unit='clips',
        tolerance=TOL_COUNT, quote='"license": "CC BY-SA 4.0"', url='', source=MANIFEST_PATH)
    add(id='C-CC0', kind='code', option='all levels', property='clips licensed CC0',
        value=sum(1 for x in _manifest() if x['license'] == 'CC0'), unit='clips',
        tolerance=TOL_COUNT, quote='"license": "CC0"', url='', source=MANIFEST_PATH)
    add(id='C-NAMED', kind='code', option='all levels',
        property='clips carrying a source, a named speaker and a licence',
        value=sum(1 for x in _manifest()
                  if x.get('source') and x.get('speaker') and x.get('license')),
        unit='clips', tolerance=TOL_COUNT, quote='"speaker": "Chen Wang"', url='',
        source=MANIFEST_PATH)
    add(id='C-ANON-L1', kind='code', option='level 1 access',
        property='levels served to a caller with no session', value=1, unit='levels',
        tolerance=TOL_COUNT,
        quote='A caller with no session gets the one level that needs no account at all',
        url='', source=ENTITLEMENT_PATH)

    # --- page rows
    add(id='P-PLANS-FREE', kind='page', option='free tier',
        property='what the free tier includes',
        value='Level 1 free, level 2 free with an account',
        quote='"tier":"free","name":"Free","description":"Level 1 free, level 2 free with an account.',
        url='https://api.tingyin.app/subscriptions/plans', source='')
    add(id='P-PLANS-WEEKLY', kind='page', option='premium, web',
        property='weekly price', value=2.49, unit='USD', quote='"id":"weekly","kind":"recurring","web":2.49',
        url='https://api.tingyin.app/subscriptions/plans', source='')
    add(id='P-PLANS-MONTHLY', kind='page', option='premium, web',
        property='monthly price', value=5.99, unit='USD',
        quote='"id":"monthly","kind":"recurring","web":5.99',
        url='https://api.tingyin.app/subscriptions/plans', source='')
    add(id='P-PLANS-LIFETIME', kind='page', option='premium, web',
        property='one-time price', value=15.99, unit='USD',
        quote='"id":"lifetime","kind":"one_time","web":15.99',
        url='https://api.tingyin.app/subscriptions/plans', source='')
    add(id='P-WONG2007', kind='page', option='Wong et al. 2007, Nature Neuroscience',
        property='what the study reports about musicians',
        value='musicians show more robust and faithful encoding compared with nonmusicians',
        quote='musicians show more robust and faithful encoding compared with nonmusicians',
        url='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=17351633&rettype=abstract&retmode=text',
        source='')
    add(id='P-WONG2007-SAMPLE', kind='page', option='Wong et al. 2007, participants',
        property='who was measured',
        value='ten amateur musicians and ten nonmusicians with no previous exposure to a tone language',
        quote='ten amateur musicians and ten nonmusicians who had no previous exposure to a tone language',
        url='https://pmc.ncbi.nlm.nih.gov/articles/PMC4508274/', source='')
    add(id='P-AMUSIA', kind='page', option='Peretz & Vuvan 2017, European Journal of Human Genetics',
        property='how common congenital amusia is',
        value='1.5% of 20 000 participants',
        quote='the prevalence of congenital amusia is only 1.5%',
        url='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=28224991&rettype=abstract&retmode=text',
        source='')
    add(id='P-WONGP2007', kind='page', option='Wong & Perrachione 2007, Applied Psycholinguistics',
        property='what predicted learning to use pitch patterns for word identification',
        value="associated with the learners' ability to perceive pitch patterns in a nonlexical context and their previous musical experience",
        quote="Learning success was found to be associated with the learners' ability to perceive pitch patterns in a nonlexical context and their previous musical experience.",
        url='https://www.cambridge.org/core/journals/applied-psycholinguistics/article/abs/learning-pitch-patterns-in-lexical-identification-by-native-englishspeaking-adults/138B3998B82E13C2F8E51256E64E35A7',
        source='')

    add(id='P-PLANS-FREE-DEVICE', kind='page', option='free tier',
        property='where free progress is kept', value='on the device only',
        quote='Your progress stays on this device.","features":{"progressSync":false',
        url='https://api.tingyin.app/subscriptions/plans', source='')
    add(id='P-PLANS-PREMIUM', kind='page', option='premium',
        property='what premium adds', value='levels 3 and 4, progress sync, offline downloads',
        quote='"features":{"progressSync":true,"offlineDownloads":true},"limits":{"maxCorpusLevel":4}',
        url='https://api.tingyin.app/subscriptions/plans', source='')
    add(id='P-AMUSIA-DIAG', kind='page', option='Peretz & Vuvan 2017, European Journal of Human Genetics',
        property='how amusia was identified', value='three objective tests and a questionnaire',
        quote='On the basis of three objective tests and a questionnaire',
        url='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=28224991&rettype=abstract&retmode=text',
        source='')
    add(id='P-AMUSIA-DEF', kind='page', option='Peretz & Vuvan 2017, European Journal of Human Genetics',
        property='what congenital amusia is', value='a lifelong musical disorder',
        quote='is a lifelong musical disorder',
        url='https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=28224991&rettype=abstract&retmode=text',
        source='')
    add(id='P-MOORE1997', kind='page', option='Moore & Jongman 1997, JASA',
        property='whether the same pitch is heard as a different tone after a different voice',
        value='identical stimuli heard as low tones after a high-pitched speaker and as high tones after a low-pitched one',
        quote='identical stimuli were identified as low tones for the high precursor condition, but as high tones for the low precursor condition',
        url='https://api.openalex.org/works/doi:10.1121/1.420092', source='https://doi.org/10.1121/1.420092')
    add(id='P-WANG1999', kind='page', option='Wang, Spence, Jongman & Sereno 1999, JASA',
        property='what two weeks of tone training did for adult English speakers',
        value='eight learners, eight sessions in two weeks, 21% higher identification accuracy, still 21% above the pretest six months later',
        quote='eight American learners of Mandarin were trained in eight sessions during the course of two weeks',
        url='https://api.openalex.org/works/doi:10.1121/1.428217', source='https://doi.org/10.1121/1.428217')
    add(id='P-WANG1999-GAIN', kind='page', option='Wang, Spence, Jongman & Sereno 1999, JASA',
        property='accuracy gain and retention', value='21% after training, 21% after six months',
        quote='revealed an average 21% increase from the pretest to the post-test',
        url='https://api.openalex.org/works/doi:10.1121/1.428217', source='https://doi.org/10.1121/1.428217')
    add(id='P-WANG1999-RETAIN', kind='page', option='Wang, Spence, Jongman & Sereno 1999, JASA',
        property='retention after six months', value='21%',
        quote='the six-month retention test showed that the improvement was retained long after training by an average 21% increase from the pretest',
        url='https://api.openalex.org/works/doi:10.1121/1.428217', source='https://doi.org/10.1121/1.428217')

    # --- product rows, from the stored output of query.js
    add(id='D-SYNCED', kind='product', option='production, user_progress',
        property='accounts with progress stored on the server', value='fewer than 10',
        unit='accounts', quote='"docs": "%s"' % SUPPRESSED, url='', source='query.js')
    add(id='D-PUBLISHABLE', kind='product', option='production, user_progress, levels 1-4',
        property='answer-count cells built from at least 10 accounts', value=0,
        unit='cells', quote='"1": "%s"' % SUPPRESSED, url='', source='query.js')

    # --- absence rows
    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='https://itunes.apple.com/lookup?bundleId=com.tingyin.app', 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="We're sorry, the requested URL was not found on this server.",
        url='https://play.google.com/store/apps/details?id=com.tingyin.app&hl=en&gl=US',
        source='')
    return rows


# ---------------------------------------------------------------- manifest helpers

_CACHE = {}


def _manifest():
    if 'm' not in _CACHE:
        _CACHE['m'] = json.loads(git_show_text(MANIFEST_PATH))
    return _CACHE['m']


def _l1():
    return [x for x in _manifest() if x['level'] == 1]


def _l2():
    return [x for x in _manifest() if x['level'] == 2]


def _l1_bases():
    """A syllable counts when the manifest holds all four tones of it."""
    by_syl = {}
    for x in _l1():
        syl = ''.join(c for c in unicodedata.normalize('NFD', x['pinyin'])
                      if not unicodedata.combining(c))
        by_syl.setdefault(syl, set()).add(x['tones'][0])
    return sum(1 for tones in by_syl.values() if tones >= {1, 2, 3, 4})


# ---------------------------------------------------------------- comparison

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


def verify(rows, lab, verbose=True):
    failures = []

    def fail(row, msg):
        failures.append((row['id'], msg))
        if verbose:
            print('FAIL %-16s %s' % (row['id'], msg))

    page_cache = {}
    for row in rows:
        kind = row['kind']
        if kind == 'lab':
            if row['id'].startswith('L-PAIR-'):
                bucket = lab['pairs_full'] if 'FULL' in row['id'] else lab['pairs_shape']
                idx = int(row['id'].rsplit('-', 1)[1]) - 1
                if idx >= len(bucket):
                    fail(row, 'rank no longer exists')
                    continue
                got = bucket[idx]['rms_st']
                if bucket[idx]['pair'] != row['option'].split()[1]:
                    fail(row, 'rank %d is now %s, was %s'
                         % (idx + 1, bucket[idx]['pair'], row['option'].split()[1]))
                elif not close(got, row['value'], row['tolerance']):
                    fail(row, 'measured %.3f, dataset %.3f' % (got, row['value']))
            else:
                tone = int(re.search(r'T(\d)', row['id']).group(1))
                prop = row['property']
                a = lab['tones'][tone]
                key = {'clips measured': 'n', 'median F0': 'median_hz',
                       'contour at the start of the nucleus': 'start_st',
                       'contour at the end of the nucleus': 'end_st',
                       'contour slope across the nucleus': 'slope_st',
                       'contour range': 'range_st',
                       'clips that dip and then rise at least 1.5 semitones': 'dip_share',
                       'position of the lowest point in the nucleus': 'min_pos'}[prop]
                got = a[key] * 100 if key == 'dip_share' else a[key]
                if not close(got, row['value'], row['tolerance']):
                    fail(row, 'measured %.3f, dataset %.3f' % (got, row['value']))
        elif kind == 'code':
            manifest = _manifest()
            fresh = {
                'C-L1-COUNT': len(_l1()),
                'C-L1-SYLL': sum(1 for x in _l1() if x['syllableCount'] == 1),
                'C-L1-BASES': _l1_bases(),
                'C-L2-COUNT': len(_l2()),
                'C-TOTAL': len(manifest),
                'C-CC-BY-SA': sum(1 for x in manifest if x['license'] == 'CC BY-SA 4.0'),
                'C-CC0': sum(1 for x in manifest if x['license'] == 'CC0'),
                'C-NAMED': sum(1 for x in manifest
                               if x.get('source') and x.get('speaker') and x.get('license')),
                'C-ANON-L1': 1,
            }[row['id']]
            if not close(fresh, row['value'], row['tolerance']):
                fail(row, 'now %s, dataset %s' % (fresh, row['value']))
            if not quote_present(git_show_text(row['source']), row['quote']):
                fail(row, 'quote gone from %s' % row['source'])
        elif kind == 'page':
            url = row['url']
            if url not in page_cache:
                try:
                    status, text = page_text(url)
                    page_cache[url] = (status, text)
                except Exception as exc:                       # noqa: BLE001
                    page_cache[url] = (None, '')
                    fail(row, 'fetch failed: %s' % exc)
                    continue
            status, text = page_cache[url]
            if not quote_present(text, row['quote']):
                fail(row, 'quote gone from %s (HTTP %s)' % (url, status))
        elif kind == 'product':
            out = product_output()
            cells = list(_user_cells(out))
            small = [c for c in cells if c != SUPPRESSED and (not isinstance(c, int) or c < MIN_USERS)]
            if small:
                fail(row, 'stored output publishes a cell under %d accounts: %s' % (MIN_USERS, small))
            if row['id'] == 'D-SYNCED':
                fresh = 'fewer than 10' if out.get('docs') == SUPPRESSED else out.get('docs')
            else:
                fresh = sum(1 for c in cells if isinstance(c, int) and c >= MIN_USERS)
            if not close(fresh, row['value'], row['tolerance']):
                fail(row, 'stored output gives %s, dataset %s' % (fresh, row['value']))
        elif kind == 'absence':
            try:
                if row['id'] == 'A-APPSTORE':
                    status, text = fetch(row['url'])
                    payload = json.loads(text)
                    if payload.get('resultCount') != 0:
                        fail(row, 'now lists %s app(s)' % payload.get('resultCount'))
                else:
                    try:
                        status, text = fetch(row['url'])
                    except urllib.error.HTTPError as exc:
                        status, text = exc.code, ''
                    if status != row['value']:
                        fail(row, 'now HTTP %s, dataset %s' % (status, row['value']))
            except Exception as exc:                           # noqa: BLE001
                fail(row, 'check failed: %s' % exc)
    return failures


# ---------------------------------------------------------------- product data

def product_output():
    with open(DATASET_JSON) as fh:
        return json.load(fh)['productData']['output']


def _user_cells(out):
    yield out.get('docs')
    for lv in out.get('levels', {}).values():
        if lv == SUPPRESSED:
            yield lv
            continue
        for b in lv.get('buckets', []):
            yield b.get('users')
        for b in lv.get('lowestToneAmongUsersWith40Plus', []):
            yield b.get('users')


# ---------------------------------------------------------------- emit

def emit(rows, lab):
    # production is not reachable from here; the redacted read is carried over unchanged
    product = json.load(open(DATASET_JSON))['productData']
    tools = {'python': sys.version.split()[0].split('+')[0],
             'numpy': np.__version__,
             'ffmpeg': _tool_version('ffmpeg')}
    item_files = ['%s/%s' % (AUDIO_DIR, x['file'])
                  for x in _manifest() if x['level'] in (1, 2)]
    inputs = [
        {'kind': 'code', 'path': MANIFEST_PATH, 'ref': REF,
         'note': 'corpus manifest: level, tones, speaker, source, licence, sha256'},
        {'kind': 'code', 'path': ENTITLEMENT_PATH, 'ref': REF,
         'note': 'which levels a caller with no session is served'},
        {'kind': 'generated', 'note': 'decoded from the 280 free-level clips below, '
         'ffmpeg to 16 kHz mono float32, in a temporary directory',
         'files': item_files},
        {'kind': 'url', 'url': 'https://api.tingyin.app/subscriptions/plans'},
        {'kind': 'url', 'url': 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
         '?db=pubmed&id=17351633&rettype=abstract&retmode=text'},
        {'kind': 'url', 'url': 'https://pmc.ncbi.nlm.nih.gov/articles/PMC4508274/'},
        {'kind': 'url', 'url': 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
         '?db=pubmed&id=28224991&rettype=abstract&retmode=text'},
        {'kind': 'url', 'url': 'https://www.cambridge.org/core/journals/applied-psycholinguistics'
         '/article/abs/learning-pitch-patterns-in-lexical-identification-by-native-englishspeaking-adults'
         '/138B3998B82E13C2F8E51256E64E35A7'},
        {'kind': 'url', 'url': 'https://api.openalex.org/works/doi:10.1121/1.420092',
         'note': 'abstract of Moore & Jongman 1997; doi.org answers curl with HTTP 403'},
        {'kind': 'url', 'url': 'https://api.openalex.org/works/doi:10.1121/1.428217',
         'note': 'abstract of Wang, Spence, Jongman & Sereno 1999; doi.org answers curl with HTTP 403'},
        {'kind': 'production', 'path': 'apps/web/public/blog/tone-deaf-mandarin/query.js',
         'note': 'read-only aggregate over the user_progress collection of the tingyin database'},
        {'kind': 'url', 'url': 'https://itunes.apple.com/lookup?bundleId=com.tingyin.app'},
        {'kind': 'url', 'url': 'https://play.google.com/store/apps/details'
         '?id=com.tingyin.app&hl=en&gl=US'},
    ]
    dataset = {
        'slug': 'tone-deaf-mandarin',
        'method': 'lab',
        'methods': ['lab', 'product-data', 'primary-docs'],
        'checkedAt': CHECKED_AT,
        'approval': 'owner, 26 October 2026, counts only',
        'question': 'Are second and third tone the hardest pair to tell apart, does each tone '
                    'have the shape the post gives it, and how fast do the product\'s own '
                    'listeners learn each tone?',
        'tools': tools,
        'inputs': inputs,
        'parameters': {
            'analysis_sample_rate_hz': SR,
            'f0_search_hz': [F0_MIN, F0_MAX],
            'frame_ms': [WIN_MS, HOP_MS],
            'voicing_threshold': VOICING,
            'nucleus_share_of_voiced_span': [NUC_START, NUC_END],
            'contour_points': N_POINTS,
            'reference': 'median F0 of the same speaker across their free-level clips',
            'dip_test': 'lowest point between 20% and 70% of the nucleus, then a rise of at '
                        'least 1.5 semitones to the end',
            'corpus': 'levels 1 and 2: 280 single-syllable clips, one speaker for 279 of them',
        },
        'results': rows,
        'productData': product,
        'notes': [
            'The audit asked for a learning curve per tone pair from answer logs. Production keeps '
            'no answer log: user_progress holds per-account counters by level and by spoken tone '
            '(asked, correct), with no record of which wrong tone was chosen, so a second-versus-'
            'third confusion cannot be counted at all. Free progress stays on the device and only '
            'premium accounts sync, and fewer than 10 accounts had a user_progress document on '
            '2026-10-26, so every count per level and per tone was suppressed and no learner '
            'figure is published.',
            'PostHog (project 552258) receives no answer event: the web app sends auth, consent, '
            'checkout and profile events only (grep of trackPostHogEvent in apps/web/src).',
            'The corpus of level 1 and level 2 clips is one voice: Chen Wang for 279 of 280 '
            'clips, CanonNi for one. A claim about how two different speakers of the same tone '
            'differ cannot be measured on it, so the post\'s central relativity claim is not '
            'covered by this check.',
            'The distance between two mean contours is a proxy for how confusable two tones '
            'are, not a listening test. It says how far apart the shapes are after every clip '
            'is put on its speaker\'s own pitch reference.',
            'Levels 3 and 4 are paid and multi-syllable, so they are left out; their speaker '
            'is a different one (Yue Tan) and no single-syllable clip of that speaker exists.',
            'PubMed\'s page for PMID 17351633 answers a script shell to curl, so the abstract '
            'is read from the E-utilities text endpoint instead.',
            'The Cambridge Core abstract is behind a paywall for the full text; only the '
            'abstract page was read, and the participants\' language is not stated there.',
        ],
    }
    with open(DATASET_JSON, 'w') as fh:
        json.dump(dataset, fh, indent=1)
        fh.write('\n')
    with open(DATASET_CSV, 'w', newline='') as fh:
        w = csv.writer(fh)
        w.writerow(['id', 'kind', 'option', 'property', 'value', 'unit', 'tolerance',
                    'quote', 'url', 'source'])
        for r in rows:
            w.writerow([r['id'], r['kind'], r['option'], r['property'], r['value'],
                        r['unit'], r['tolerance'], r['quote'], r['url'], r['source']])
    print('wrote %s (%d rows) and %s' % (DATASET_JSON, len(rows), DATASET_CSV))


def _tool_version(name):
    out = subprocess.run([name, '-version'], capture_output=True, text=True).stdout
    return out.splitlines()[0].split(' Copyright')[0].replace('ffmpeg version ', '') \
        if out else 'unknown'


# ---------------------------------------------------------------- main

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

    print('measuring %s levels 1-2 ...' % REF)
    lab = measure_lab()
    print('  %d clips, %.1fs, reference pitch %s'
          % (lab['clips_measured'], lab['elapsed_s'],
             {k: round(v, 1) for k, v in lab['reference_hz'].items()}))
    for tone, a in sorted(lab['tones'].items()):
        print('  tone %d  n=%d  median %.1f Hz  start %+.2f  end %+.2f  slope %+.2f  '
              'range %.2f  dip %.2f'
              % (tone, a['n'], a['median_hz'], a['start_st'], a['end_st'],
                 a['slope_st'], a['range_st'], a['dip_share']))
    print('  full contour, closest pair first: '
          + ', '.join('%s %.2f' % (p['pair'], p['rms_st']) for p in lab['pairs_full']))
    print('  shape only, closest pair first:   '
          + ', '.join('%s %.2f' % (p['pair'], p['rms_st']) for p in lab['pairs_shape']))

    rows = build_rows(lab)
    if args.emit:
        emit(rows, lab)
        return 0

    with open(DATASET_JSON) as fh:
        stored = json.load(fh)['results']
    print('checking %d rows against dataset.json' % len(stored))
    failures = verify(stored, lab)
    if failures:
        print('\n%d row(s) failed' % len(failures))
        return 1
    print('all %d rows hold' % len(stored))
    return 0


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