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

Rows in dataset.json come in four kinds:

  code      counts read out of the product repository with `git show origin/main:`:
            fixtures/audio-manifest.json, apps/api/src/corpus/corpus.generated.ts and
            a grep over apps/web/src proved no microphone call exists in the exercise
  lab       the free level's own clips (80 mp3 in apps/web/public/audio), decoded and
            measured here: the pitch gap between two tones of the same syllable, and a
            simulation of the shuffled-run claim in the post
  page      an exact sentence on a URL, re-fetched and compared after normalisation
  absence   neither store has a listing for the app's bundle id

Exit 0 when every row still holds, 1 otherwise. `--recheck` runs the same work; the
lab step takes about 30 s on this Mac, under the one-minute budget, so nothing is
skipped. `--emit` rewrites dataset.json and dataset.csv from a fresh measurement.

Run it from anywhere inside a clone of the Tingyin repository, or point TINGYIN_REPO at
one. Standard library plus numpy; ffmpeg decodes the mp3 clips.
"""

import argparse
import atexit
import csv
import html
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
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 = os.environ.get('TINGYIN_REPO') or subprocess.run(
    ['git', '-C', HERE, 'rev-parse', '--show-toplevel'],
    capture_output=True, text=True).stdout.strip()
CLIPS = tempfile.mkdtemp(prefix='tingyin-l1-')
atexit.register(shutil.rmtree, CLIPS, True)
REF = 'origin/main'
MANIFEST_PATH = 'fixtures/audio-manifest.json'
CORPUS_PATH = 'apps/api/src/corpus/corpus.generated.ts'

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

# ---- pitch measurement, fixed here so a re-run measures the same thing
SR = 16000
WIN, HOP = 1024, 160
F0_MIN, F0_MAX = 70.0, 400.0
CMND_THRESHOLD = 0.5      # YIN aperiodicity below which a frame counts as voiced
LOUD_DB = -25.0           # frames within this many dB of the clip's peak
N_CONTOUR = 20
SHUFFLE_TRIALS = 20000
SHUFFLE_SEED = 20261026

TOL_ST = 0.20             # a different ffmpeg or BLAS build moves the last decimal
TOL_SHUFFLE = 0.15
TOL_COUNT = 0
TOL_SHARE = 0

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


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

def fetch(url, timeout=60):
    req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': '*/*'})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.read().decode('utf-8', errors='replace')
    except urllib.error.HTTPError as exc:
        # a 404 is the answer for an absence row, not a failure to ask
        return exc.code, exc.read().decode('utf-8', errors='replace')


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)
    # a tag between a word and its comma leaves a space the quote does not have
    t = re.sub(r'\s+([,.;:!?])', r'\1', t)
    return t.strip()


def page_text(url):
    """The text a quote is compared against; OpenAlex abstracts are inverted indexes."""
    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).stdout.decode('utf-8', errors='replace')


def git_grep_count(pattern, pathspec):
    r = subprocess.run(['git', '-C', REPO, 'grep', '-l', '-E', pattern, REF, '--'] + pathspec,
                       capture_output=True, text=True)
    if r.returncode not in (0, 1):
        raise RuntimeError(r.stderr)
    hits = [l for l in r.stdout.splitlines() if l.strip()]
    # blog prose talks about microphones; only the app's own code counts here
    return len([l for l in hits if '/lib/blog/' not in l and '__tests__' not in l])


# ---------------------------------------------------------------- code rows

def corpus_items():
    raw = git_show(CORPUS_PATH)
    objs = re.findall(r'\{\s*"id":.*?\n  \}', raw, re.S)
    items = []
    for o in objs:
        o = re.sub(r'(\n\s*)([a-zA-Z]+):', r'\1"\2":', o.strip().rstrip(','))
        items.append(json.loads(o))
    return items


def manifest_items():
    return json.loads(git_show(MANIFEST_PATH))


def pinyin_base(p):
    t = unicodedata.normalize('NFKD', p)
    return ''.join(c for c in t if not unicodedata.combining(c)).replace(' ', '').lower()


def code_values():
    items = corpus_items()
    man = manifest_items()
    multi = [i for i in items if i['syllableCount'] > 1]
    sandhi = [i for i in items if i.get('sandhi')]
    mismatch = [i for i in items if i.get('citationTones') != i['tones']]
    neutral = [i for i in items if 5 in i['tones']]
    l1 = [i for i in items if i['level'] == 1]
    l1_groups = {}
    for i in l1:
        l1_groups.setdefault(pinyin_base(i['pinyin']), set()).add(tuple(i['tones']))
    two_syl = set(tuple(i['tones']) for i in items if i['syllableCount'] == 2)
    by_count = {}
    for i in items:
        by_count[i['syllableCount']] = by_count.get(i['syllableCount'], 0) + 1
    complete = [i for i in man if all(i.get(k) for k in ('source', 'speaker', 'license', 'sha256'))]
    lic = {}
    for i in man:
        lic[i['license']] = lic.get(i['license'], 0) + 1
    return {
        'items': len(items),
        'single': by_count.get(1, 0),
        'two': by_count.get(2, 0),
        'three': by_count.get(3, 0),
        'four': by_count.get(4, 0),
        'sandhi': len(sandhi),
        'mismatch_multi': len([i for i in mismatch if i['syllableCount'] > 1]),
        'multi': len(multi),
        'neutral': len(neutral),
        'neutral_min_syl': min(i['syllableCount'] for i in neutral),
        't33_spoken': len([i for i in items if i['tones'] == [3, 3]]),
        't33_citation': len([i for i in items if i.get('citationTones') == [3, 3]]),
        'two_syl_combos': len(two_syl),
        'lic_cc_by_sa': lic.get('CC BY-SA 4.0', 0),
        'lic_cc0': lic.get('CC0', 0),
        'metadata_complete': len(complete),
        'l1_clips': len(l1),
        'l1_groups': len(l1_groups),
        'l1_group_tone_sets': sorted(set(len(v) for v in l1_groups.values())),
        'microphone_calls': git_grep_count(r'getUserMedia|MediaRecorder|navigator\.mediaDevices',
                                          ['apps/web/src']),
    }


# ---------------------------------------------------------------- lab: pitch

def load_audio(path):
    r = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR),
                        '-f', 'f32le', '-'], capture_output=True)
    if r.returncode != 0:
        raise RuntimeError('ffmpeg failed on %s: %s' % (path, r.stderr.decode()[:200]))
    return np.frombuffer(r.stdout, dtype=np.float32).astype(np.float64)


TAU_MIN = int(SR / F0_MAX)
TAU_MAX = int(SR / F0_MIN)


def yin_frame(s):
    w = len(s)
    nfft = 1
    while nfft < 2 * w:
        nfft *= 2
    spec = np.fft.rfft(s, nfft)
    ac = np.fft.irfft(spec * np.conj(spec), nfft)[:w]
    sq = np.concatenate([[0.0], np.cumsum(s * s)])
    taus = np.arange(TAU_MAX + 1)
    d = sq[w - taus] + (sq[w] - sq[taus]) - 2 * ac[:TAU_MAX + 1]
    d[0] = 0.0
    cs = np.cumsum(d[1:])
    cm = np.ones(TAU_MAX + 1)
    cm[1:] = d[1:] * taus[1:] / np.maximum(cs, 1e-12)
    cand = np.where(cm[TAU_MIN:] < 0.15)[0]
    ti = int(cand[0]) + TAU_MIN if len(cand) else int(np.argmin(cm[TAU_MIN:])) + TAU_MIN
    tf = float(ti)
    if 1 <= ti < TAU_MAX:
        a, b, c = cm[ti - 1], cm[ti], cm[ti + 1]
        den = a - 2 * b + c
        if abs(den) > 1e-12:
            tf = ti + 0.5 * (a - c) / den
    return SR / tf, float(cm[ti])


def pitch_track(x):
    frames = 1 + (len(x) - WIN) // HOP
    f0 = np.zeros(frames)
    aper = np.ones(frames)
    for i in range(frames):
        s = x[i * HOP:i * HOP + WIN]
        s = s - s.mean()
        if np.sqrt((s * s).mean()) < 1e-3:
            continue
        f, a = yin_frame(s)
        f0[i], aper[i] = f, a
    rms = np.array([np.sqrt(np.mean(x[i * HOP:i * HOP + WIN] ** 2)) for i in range(frames)])
    return f0, aper, rms


def clip_features(path):
    f0, aper, rms = pitch_track(load_audio(path))
    loud = rms > rms.max() * 10 ** (LOUD_DB / 20)
    ok = loud & (aper < CMND_THRESHOLD) & (f0 >= F0_MIN) & (f0 <= F0_MAX)
    idx = np.where(ok)[0]
    if len(idx) < 10:
        return None
    span = slice(idx[0], idx[-1] + 1)
    vals = f0[span][ok[span]]
    if len(vals) < 10:
        return None
    med = float(np.median(vals))
    st = 12 * np.log2(vals / med)
    cont = np.interp(np.linspace(0, 1, N_CONTOUR), np.linspace(0, 1, len(st)), st)
    return med, cont


def tone_pair_values():
    man = manifest_items()
    l1 = [e for e in man if e['level'] == 1]
    groups = {}
    for e in l1:
        feat = clip_features(os.path.join(CLIPS, e['file']))
        if feat is None:
            raise RuntimeError('no pitch track for %s' % e['file'])
        groups.setdefault(pinyin_base(e['pinyin']), {})[e['tones'][0]] = feat
    out = {'t3_lowest': sum(1 for d in groups.values() if min(d, key=lambda t: d[t][0]) == 3)}
    for a in (1, 2, 3, 4):
        for b in (1, 2, 3, 4):
            if a >= b:
                continue
            lev, con = [], []
            for _syl, d in groups.items():
                if a in d and b in d:
                    ma, ca = d[a]
                    mb, cb = d[b]
                    lev.append(abs(12 * np.log2(ma / mb)))
                    con.append(float(np.sqrt(np.mean((ca - cb) ** 2))))
            out[(a, b)] = (round(float(np.median(lev)), 2),
                           round(float(np.median(con)), 2), len(lev))
    return out


def extract_clips():
    """The clips are committed in the product repository; copy the free level out."""
    out = CLIPS
    for e in [i for i in manifest_items() if i['level'] == 1]:
        path = os.path.join(out, e['file'])
        if os.path.exists(path) and os.path.getsize(path) > 1000:
            continue
        r = subprocess.run(['git', '-C', REPO, 'show',
                            '%s:%s' % (REF, 'apps/web/public/audio/' + e['file'])],
                           capture_output=True)
        if r.returncode != 0:
            raise RuntimeError('clip missing from %s: %s' % (REF, e['file']))
        with open(path, 'wb') as fh:
            fh.write(r.stdout)
    return len(os.listdir(out))


def shuffle_runs():
    """Maximal runs of three or more of one tone in a shuffled 100-item drill."""
    def runs(seq):
        n, i = 0, 0
        while i < len(seq):
            j = i
            while j + 1 < len(seq) and seq[j + 1] == seq[i]:
                j += 1
            if j - i + 1 >= 3:
                n += 1
            i = j + 1
        return n

    base = [1] * 25 + [2] * 25 + [3] * 25 + [4] * 25
    rnd = random.Random(SHUFFLE_SEED)
    vals = []
    for _ in range(SHUFFLE_TRIALS):
        s = base[:]
        rnd.shuffle(s)
        vals.append(runs(s))
    return round(float(np.mean(vals)), 2), int(np.median(vals))


# ---------------------------------------------------------------- the rows

def build_rows():
    cv = code_values()
    clips = extract_clips()
    if clips < 80:
        raise RuntimeError('expected 80 free-level clips, extracted %d' % clips)
    pairs = tone_pair_values()
    shuffle_mean, shuffle_median = shuffle_runs()

    rows = []

    def code(id_, option, prop, value, unit, quote, source):
        rows.append({'id': id_, 'kind': 'code', 'option': option, 'property': prop,
                     'value': value, 'unit': unit, 'tolerance': TOL_COUNT,
                     'quote': quote, 'url': '', 'source': source})

    def page(id_, option, prop, value, unit, quote, url, tol=TOL_SHARE):
        rows.append({'id': id_, 'kind': 'page', 'option': option, 'property': prop,
                     'value': value, 'unit': unit, 'tolerance': tol,
                     'quote': quote, 'url': url, 'source': url})

    def lab(id_, option, prop, value, unit, tol, quote):
        rows.append({'id': id_, 'kind': 'lab', 'option': option, 'property': prop,
                     'value': value, 'unit': unit, 'tolerance': tol,
                     'quote': quote, 'url': '', 'source': 'measured here from the product clips'})

    # -- the product's own corpus, read from the repository
    code('C-ITEMS', 'Tingyin corpus', 'clips in the manifest', cv['items'], 'clips',
         'all 637 clips', MANIFEST_PATH)
    code('C-SYL-1', 'Tingyin corpus', 'one-syllable clips', cv['single'], 'clips', '280', CORPUS_PATH)
    code('C-SYL-2', 'Tingyin corpus', 'two-syllable clips', cv['two'], 'clips', '237', CORPUS_PATH)
    code('C-SYL-3', 'Tingyin corpus', 'three-syllable clips', cv['three'], 'clips', '107', CORPUS_PATH)
    code('C-SYL-4', 'Tingyin corpus', 'four-syllable clips', cv['four'], 'clips', '13', CORPUS_PATH)
    code('C-SANDHI', 'Tingyin corpus', 'clips with sandhi applied', cv['sandhi'], 'clips', '55', CORPUS_PATH)
    code('C-MISMATCH', 'Tingyin corpus', 'multi-syllable clips whose written tone differs from the spoken one',
         cv['mismatch_multi'], 'clips', '55 of the 357', CORPUS_PATH)
    code('C-MULTI', 'Tingyin corpus', 'clips longer than one syllable', cv['multi'], 'clips', '357', CORPUS_PATH)
    code('C-NEUTRAL', 'Tingyin corpus', 'clips containing a neutral tone', cv['neutral'], 'clips', '80', CORPUS_PATH)
    code('C-NEUTRAL-MIN', 'Tingyin corpus', 'shortest clip containing a neutral tone', cv['neutral_min_syl'],
         'syllables', 'at least two syllables long', CORPUS_PATH)
    code('C-T33-SPOKEN', 'Tingyin corpus', 'clips labelled third-then-third', cv['t33_spoken'], 'clips',
         'not a single one labelled third-then-third', CORPUS_PATH)
    code('C-T33-CITATION', 'Tingyin corpus', 'clips whose written form is third-then-third',
         cv['t33_citation'], 'clips', 'written 3+3 is stored as 2+3', CORPUS_PATH)
    code('C-TWO-COMBOS', 'Tingyin corpus', 'distinct two-syllable tone combinations present',
         cv['two_syl_combos'], 'combinations', 'nineteen of the twenty', CORPUS_PATH)
    code('C-LIC-CCBYSA', 'Tingyin corpus', 'clips under CC BY-SA 4.0', cv['lic_cc_by_sa'], 'clips', '622', MANIFEST_PATH)
    code('C-LIC-CC0', 'Tingyin corpus', 'clips under CC0', cv['lic_cc0'], 'clips', '15', MANIFEST_PATH)
    code('C-META', 'Tingyin corpus', 'clips carrying source, speaker, licence and sha256',
         cv['metadata_complete'], 'clips', 'each carries its source, speaker, licence and a content hash',
         MANIFEST_PATH)
    code('C-L1-CLIPS', 'Tingyin level 1', 'clips', cv['l1_clips'], 'clips',
         '80 single-syllable clips', CORPUS_PATH)
    code('C-L1-GROUPS', 'Tingyin level 1', 'syllables present in all four tones', cv['l1_groups'], 'syllables',
         'the same syllable presented in each of its tones', CORPUS_PATH)
    code('C-NOMIC', 'Tingyin exercise', 'microphone or recorder calls in the web app source',
         cv['microphone_calls'], 'files', 'there is no microphone in the exercise', 'apps/web/src')

    # -- lab: the free level's own audio
    t3_lowest = pairs.pop('t3_lowest')
    for (a, b), (lev, con, n) in sorted(pairs.items()):
        lab('L-LEVEL-%d%d' % (a, b), 'tones %d and %d' % (a, b),
            'median pitch-level gap on the same syllable', lev, 'semitones', TOL_ST,
            'level gap measured over %d syllables' % n)
        lab('L-CONTOUR-%d%d' % (a, b), 'tones %d and %d' % (a, b),
            'median contour gap on the same syllable', con, 'semitones', TOL_ST,
            'contour RMS measured over %d syllables' % n)
    lab('L-T3-LOWEST', 'tone 3', 'syllables where tone 3 has the lowest median pitch of the four',
        t3_lowest, 'syllables', TOL_COUNT, 'the lowest thing you will be asked to judge')
    lab('L-SHUFFLE', 'a shuffled 100-item drill', 'stretches of the same tone three or more times in a row',
        shuffle_mean, 'stretches', TOL_SHUFFLE,
        'mean of %d shuffles, seed %d, median %d' % (SHUFFLE_TRIALS, SHUFFLE_SEED, shuffle_median))

    # -- pages
    page('P-ANKI', 'Anki', 'spaced repetition', 'yes', 'verdict',
         'The first one is based on the SuperMemo 2 algorithm, and the second one is called FSRS.',
         'https://docs.ankiweb.net/faqs/what-spaced-repetition-algorithm')
    page('P-WANG-DESIGN', 'Wang, Jongman & Sereno 1999', 'eight sessions over two weeks, no production training',
         'yes', 'verdict',
         'trained in eight sessions during the course of two weeks to identify the four tones in '
         'natural words produced by native Mandarin talkers',
         'https://api.openalex.org/works/W2029908195')
    page('P-WANG-VARIABILITY', 'Wang, Jongman & Sereno 1999', 'training used several native talkers',
         'yes', 'verdict', 'Using the high-variability paradigm',
         'https://api.openalex.org/works/W2029908195')
    page('P-WANG-GAIN', 'Wang, Jongman & Sereno 1999', 'identification accuracy gain, pretest to post-test',
         21, 'percent', "The trainees' identification accuracy revealed an average 21% increase from the "
         'pretest to the post-test',
         'https://api.openalex.org/works/W2029908195')
    page('P-WANG-NEW-TALKERS', 'Wang, Jongman & Sereno 1999', 'gain on new talkers and stimuli',
         25, 'percent', 'to new talkers and stimuli (25% increase)',
         'https://api.openalex.org/works/W2029908195')
    page('P-WANG-TRANSFER', 'Wang, Jongman & Sereno 2003', 'gain in native judges identifying the trainees\' productions',
         18, 'percent',
         "Identification of trainees' post-test tone productions improved by 18% relative to their "
         "pretest productions",
         'https://api.openalex.org/works/W2042681535')
    page('P-WANG-HEIGHT', 'Wang, Jongman & Sereno 2003', 'pitch height harder to improve than contour',
         'yes', 'verdict', 'with the former being more resistant to improvement than the latter',
         'https://api.openalex.org/works/W2042681535')
    page('P-TINGYIN-FREE', 'Tingyin', 'level 1 free without an account, level 2 free with one', 'yes', 'verdict',
         'Level 1 free, level 2 free with an account.',
         'https://api.tingyin.app/subscriptions/plans')
    page('P-TINGYIN-MONTHLY', 'Tingyin', 'monthly price on the web', 5.99, 'USD',
         '"monthly","kind":"recurring","web":5.99', 'https://api.tingyin.app/subscriptions/plans')
    page('P-TINGYIN-LIFETIME', 'Tingyin', 'one-time price on the web', 15.99, 'USD',
         '"lifetime","kind":"one_time","web":15.99', 'https://api.tingyin.app/subscriptions/plans')
    rows.append({'id': 'A-PLAY', 'kind': 'absence', 'option': 'Android app',
                 'property': 'Google Play listing for com.tingyin.app', 'value': 404,
                 'unit': 'HTTP status', 'tolerance': 0,
                 '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',
                 'source': 'Google Play'})
    rows.append({'id': 'A-APPSTORE', 'kind': 'absence', 'option': 'iOS app',
                 'property': 'App Store listings for the bundle id com.tingyin.app', 'value': 0,
                 'unit': 'listings', 'tolerance': 0, 'quote': '"resultCount":0',
                 'url': 'https://itunes.apple.com/lookup?bundleId=com.tingyin.app',
                 'source': 'iTunes lookup'})
    return rows


# ---------------------------------------------------------------- verify

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


def verify(rows):
    failures = []
    cache = {}

    for r in rows:
        kind = r['kind']
        if kind == 'code':
            continue  # recomputed below in one pass
        if kind in ('page', 'absence'):
            url = r['url']
            try:
                if url not in cache:
                    cache[url] = page_text(url)
                status, text = cache[url]
            except Exception as exc:
                failures.append('%s: fetch failed for %s (%s)' % (r['id'], url, exc))
                continue
            if kind == 'absence':
                if r['unit'] == 'HTTP status':
                    ok = close(status, r['value'], 0) and normalise(r['quote']) in normalise(text)
                else:
                    ok = status == 200 and normalise(r['quote']) in normalise(text)
            else:
                ok = normalise(r['quote']) in normalise(text)
            if not ok:
                # one retry: a store or docs page occasionally answers with a stub
                try:
                    status2, text2 = page_text(url)
                    if kind == 'absence':
                        if r['unit'] == 'HTTP status':
                            ok = close(status2, r['value'], 0) and normalise(r['quote']) in normalise(text2)
                        else:
                            ok = status2 == 200 and normalise(r['quote']) in normalise(text2)
                    else:
                        ok = normalise(r['quote']) in normalise(text2)
                except Exception:
                    pass
            if not ok:
                failures.append('%s: quote gone from %s' % (r['id'], url))
        elif kind == 'lab':
            pass  # compared in verify_lab

    return failures


def verify_lab(rows):
    failures = []
    pairs = tone_pair_values()
    shuffle_mean, _median = shuffle_runs()
    for r in rows:
        if r['kind'] != 'lab':
            continue
        if r['id'] == 'L-T3-LOWEST':
            if not close(pairs['t3_lowest'], r['value'], r['tolerance']):
                failures.append('%s: measured %s, dataset says %s' % (r['id'], pairs['t3_lowest'], r['value']))
            continue
        if r['id'] == 'L-SHUFFLE':
            if not close(shuffle_mean, r['value'], r['tolerance']):
                failures.append('%s: measured %.2f, dataset says %s' % (r['id'], shuffle_mean, r['value']))
            continue
        key = r['id'].split('-')[-1]
        a, b = int(key[0]), int(key[1])
        lev, con, _n = pairs[(a, b)]
        got = lev if r['id'].startswith('L-LEVEL') else con
        if not close(got, r['value'], r['tolerance']):
            failures.append('%s: measured %.2f, dataset says %s' % (r['id'], got, r['value']))
    return failures


def verify_code(rows):
    failures = []
    cv = code_values()
    mapping = {
        'C-ITEMS': cv['items'], 'C-SYL-1': cv['single'], 'C-SYL-2': cv['two'],
        'C-SYL-3': cv['three'], 'C-SYL-4': cv['four'], 'C-SANDHI': cv['sandhi'],
        'C-MISMATCH': cv['mismatch_multi'], 'C-MULTI': cv['multi'],
        'C-NEUTRAL': cv['neutral'], 'C-NEUTRAL-MIN': cv['neutral_min_syl'],
        'C-T33-SPOKEN': cv['t33_spoken'], 'C-T33-CITATION': cv['t33_citation'],
        'C-TWO-COMBOS': cv['two_syl_combos'], 'C-LIC-CCBYSA': cv['lic_cc_by_sa'],
        'C-LIC-CC0': cv['lic_cc0'], 'C-META': cv['metadata_complete'],
        'C-L1-CLIPS': cv['l1_clips'], 'C-L1-GROUPS': cv['l1_groups'],
        'C-NOMIC': cv['microphone_calls'],
    }
    for r in rows:
        if r['kind'] != 'code':
            continue
        got = mapping[r['id']]
        if not close(got, r['value'], r['tolerance']):
            failures.append('%s: measured %s, dataset says %s' % (r['id'], got, r['value']))
    return failures


# ---------------------------------------------------------------- write

def write_dataset(rows, tools, inputs, notes):
    data = {'method': 'lab', 'checkedAt': CHECKED_AT, 'tools': tools,
            'inputs': inputs, 'results': rows, 'notes': notes}
    with open(DATASET_JSON, 'w', encoding='utf-8') as fh:
        json.dump(data, fh, indent=1, ensure_ascii=False)
        fh.write('\n')
    cols = ['id', 'kind', 'option', 'property', 'value', 'unit', 'tolerance', 'quote', 'url', 'source']
    with open(DATASET_CSV, 'w', newline='', encoding='utf-8') as fh:
        w = csv.DictWriter(fh, fieldnames=cols, extrasaction='ignore')
        w.writeheader()
        for r in rows:
            w.writerow(r)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--recheck', action='store_true')
    ap.add_argument('--emit', action='store_true')
    args = ap.parse_args()

    if not args.emit:
        extract_clips()
        stored = json.load(open(DATASET_JSON, encoding='utf-8'))['results']
        failures = []
        try:
            failures += verify(stored)
            failures += verify_code(stored)
            failures += verify_lab(stored)
        except Exception as exc:
            failures.append('check crashed: %s' % exc)
        if failures:
            print('FAIL (%d)' % len(failures))
            for f in failures:
                print('  ' + f)
            return 1
        print('OK: %d rows hold%s' % (len(stored), ' (recheck)' if args.recheck else ''))
        return 0

    rows = build_rows()

    if args.emit:
        tools = {
            'python': sys.version.split()[0],
            'numpy': np.__version__,
            'ffmpeg': subprocess.run(['ffmpeg', '-version'], capture_output=True, text=True
                                     ).stdout.splitlines()[0],
            'git': subprocess.run(['git', '--version'], capture_output=True, text=True).stdout.strip(),
        }
        inputs = [
            'git show %s:%s' % (REF, MANIFEST_PATH),
            'git show %s:%s' % (REF, CORPUS_PATH),
            'git show %s:apps/web/public/audio/l1-*.mp3 (the 80 level-1 clips)' % REF,
            'git grep over %s:apps/web/src' % REF,
        ] + sorted({r['url'] for r in rows if r['url']})
        notes = json.load(open(DATASET_JSON, encoding='utf-8'))['notes']
        write_dataset(rows, tools, inputs, notes)
        print('wrote %s and %s (%d rows)' % (DATASET_JSON, DATASET_CSV, len(rows)))
        return 0

    return 0


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