#!/usr/bin/env python3
"""Evidence check for the Tingyin post mandarin-vs-cantonese-tones.

Four parts:
  pages     every cited sentence is re-fetched from its page and searched for;
  licences  the licence of every measured recording is re-read from Wikimedia Commons;
  lab       the pitch of Cantonese tones 1, 3 and 6 is re-measured on the same recordings;
  product   the Tingyin facts the post states are re-counted, when run inside the repository.

Exit 0 when every quote is still on its page, every licence is unchanged and every
measured value still matches dataset.json; 1 otherwise.  --recheck re-reads the pages
and the licences, and re-measures only when the audio is already cached, so it never
spends minutes downloading.  --record rewrites dataset.json and dataset.csv.

Needs Python 3.9+, numpy and ffmpeg on PATH.
"""
import argparse
import csv
import hashlib
import html as htmlmod
import io
import json
import math
import os
import re
import subprocess
import sys
import tempfile
import time
import unicodedata
import urllib.parse
import urllib.request
import wave

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, 'dataset.json')
CSV_PATH = os.path.join(HERE, 'dataset.csv')
# The audio cache stays outside public/ so it is never served.
CACHE = os.environ.get('MVCT_CACHE') or os.path.join(
    tempfile.gettempdir(), 'tingyin-mandarin-vs-cantonese-tones-audio')
REPO = os.path.abspath(os.path.join(HERE, '..', '..', '..', '..', '..'))
UA = 'TingyinResearch/1.0 (https://tingyin.app) article-quality-evidence'
CHECKED_AT = '2026-10-26'

# --- pitch measurement -------------------------------------------------------
SR = 22050
FRAME_S = 0.045
HOP_S = 0.010
F0_LO, F0_HI = 60.0, 500.0
RMS_MIN = 0.01
ACCEPT = 0.5
TRIM = 0.2          # the middle 60 % of the voiced run


def fetch(url, timeout=45, tries=6):
    last = None
    for attempt in range(tries):
        req = urllib.request.Request(url, headers={'User-Agent': UA})
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return r.read()
        except Exception as exc:            # 429 from Wikimedia, resets
            last = exc
            if attempt < tries - 1:
                time.sleep(2 + attempt * 4)
    raise RuntimeError(f'{url}: {last}')


def normalise(s):
    s = htmlmod.unescape(s)
    s = unicodedata.normalize('NFC', s)
    for a, b in (('\u2019', "'"), ('\u2018', "'"), ('\u201c', '"'), ('\u201d', '"'),
                 ('\u2013', '-'), ('\u2014', '-'), ('\u00a0', ' ')):
        s = s.replace(a, b)
    return re.sub(r'\s+', ' ', s).strip()


def page_text(raw):
    t = raw.decode('utf-8', 'replace')
    t = re.sub(r'(?is)<(script|style)[^>]*>.*?</\1>', ' ', t)
    t = re.sub(r'(?s)<[^>]+>', ' ', t)
    return normalise(t)


def quote_present(text, quote):
    t, q = normalise(text), normalise(quote)
    if q in t:
        return True
    return re.sub(r'\s+', '', q) in re.sub(r'\s+', '', t)


# --- audio ------------------------------------------------------------------
def load_audio(path, np):
    proc = subprocess.run(
        ['ffmpeg', '-v', 'error', '-i', path, '-ac', '1', '-ar', str(SR), '-f', 'wav', '-'],
        capture_output=True, check=True)
    w = wave.open(io.BytesIO(proc.stdout), 'rb')
    return np.frombuffer(w.readframes(w.getnframes()), dtype='<i2').astype('float64') / 32768.0


def f0_track(x, np):
    n, h = int(FRAME_S * SR), int(HOP_S * SR)
    lag_lo, lag_hi = int(SR / F0_HI), int(SR / F0_LO)
    out = []
    for start in range(0, max(0, len(x) - n), h):
        fr = x[start:start + n]
        if np.sqrt(np.mean(fr ** 2)) < RMS_MIN:
            out.append((start / SR, 0.0, 0.0))
            continue
        fr = fr - fr.mean()
        ac = np.correlate(fr, fr, 'full')[n - 1:]
        ac = ac / (ac[0] + 1e-12)
        k = int(np.argmax(ac[lag_lo:lag_hi])) + lag_lo
        f0 = SR / k
        if 0 < k < len(ac) - 1:
            a, b, c = ac[k - 1], ac[k], ac[k + 1]
            den = a - 2 * b + c
            if den != 0:
                f0 = SR / (k + 0.5 * (a - c) / den)
        out.append((start / SR, f0, float(ac[k])))
    return out


def analyse(path):
    np = __import__('numpy')
    x = load_audio(path, np)
    voiced = [(t, f0) for t, f0, r in f0_track(x, np) if r >= ACCEPT and f0 > 0]
    if len(voiced) < 8:
        raise RuntimeError(f'{path}: only {len(voiced)} voiced frames')
    t0, t1 = voiced[0][0], voiced[-1][0]
    lo, hi = t0 + TRIM * (t1 - t0), t0 + (1 - TRIM) * (t1 - t0)
    mid = [f0 for t, f0 in voiced if lo <= t <= hi]
    vals = np.array(mid if len(mid) >= 5 else [f0 for _, f0 in voiced])
    return {
        'median_hz': round(float(np.median(vals)), 1),
        'sd_hz': round(float(np.std(vals)), 1),
        'frames': len(voiced),
    }


def st(a, b):
    return 12.0 * math.log2(a / b)


# --- corpus -----------------------------------------------------------------
BASE = 'https://upload.wikimedia.org/wikipedia/commons/'
JY = 'Jyugulik'
JY_URLS = {
    'chaang1': '5/54', 'chaang2': '6/67', 'chaang3': '3/39', 'chaang4': 'b/b4',
    'chaang5': '4/40', 'chaang6': '3/39',
    'cho1': 'f/fa', 'cho2': '2/26', 'cho3': '7/77', 'cho5': '2/25', 'cho6': 'd/d6',
    'faan1': 'f/fd', 'faan2': '4/46', 'faan3': '5/58', 'faan4': '0/07', 'faan5': 'a/ac', 'faan6': '6/6c',
    'fu1': 'f/fd', 'fu2': '4/41', 'fu3': 'e/e7', 'fu4': '6/60', 'fu5': '1/17', 'fu6': '2/24',
}

FETE_URLS = [
    'https://upload.wikimedia.org/wikipedia/commons/f/f5/Yue-%E4%BD%8E.oga',
    'https://upload.wikimedia.org/wikipedia/commons/9/92/Yue-%E9%9B%9E.oga',
    'https://upload.wikimedia.org/wikipedia/commons/e/ea/Yue-%E8%BC%9D.oga',
    'https://upload.wikimedia.org/wikipedia/commons/c/cb/Yue-%E9%80%81.oga',
    'https://upload.wikimedia.org/wikipedia/commons/1/10/Yue-kek6.ogg',
]

LL_FILES = [
    ('Jonashtand', '一', '8/83'), ('Jonashtand', '你哋', 'c/c0'), ('Jonashtand', '勉強', 'd/de'),
    ('Jonashtand', '唔係', '0/05'), ('Jonashtand', '夏天', '9/9a'), ('Jonashtand', '少女', '1/16'),
    ('Jonashtand', '感謝', '1/11'), ('Jonashtand', '日頭', '7/7e'), ('Jonashtand', '樹枝', '7/76'),
    ('Jonashtand', '海', '6/6b'), ('Jonashtand', '生產', '5/59'), ('Jonashtand', '系統', 'e/e7'),
    ('JDsonical', '中山', '4/4a'), ('JDsonical', '佛山', 'f/fe'), ('JDsonical', '廣州', 'b/b7'),
    ('JDsonical', '惠州', '9/91'), ('JDsonical', '揭陽', '1/10'), ('JDsonical', '東莞', '8/8b'),
    ('JDsonical', '梅州', 'e/e4'), ('JDsonical', '汕尾', '2/2c'), ('JDsonical', '汕頭', 'f/f5'),
    ('JDsonical', '江門', '9/96'), ('JDsonical', '河源', '6/68'), ('JDsonical', '深圳', '2/26'),
    ('DaphosGC', 'little', '3/3f'), ('DaphosGC', 'my', 'c/c6'), ('DaphosGC', 'pony', '2/2c'),
    ('DaphosGC', '卑利街', '8/8d'), ('DaphosGC', '封閉道路通行許可證', 'f/f8'),
    ('DaphosGC', '路政署', '8/87'), ('DaphosGC', '路段', '8/8b'), ('DaphosGC', '長命斜', '8/8f'),
    ('DaphosGC', '青沙管制區', 'c/c6'), ('DaphosGC', '青馬管制區', '0/04'),
    ('DaphosGC', '香港主要幹道', '3/3f'), ('DaphosGC', '香港公路', '5/58'),
]


def corpus():
    """(key, speaker, url) for every recording measured."""
    items = []
    for key, path in JY_URLS.items():
        items.append((key, JY, f'{BASE}{path}/Yue-{key}.ogg'))
    for i, url in enumerate(FETE_URLS, 1):
        items.append((f'fete{i}', 'Fête', url))
    for speaker, word, path in LL_FILES:
        name = urllib.parse.quote(f'LL-Q9186 (yue)-{speaker}-{word}.wav')
        items.append((f'{speaker}-{word}', speaker, f'{BASE}{path}/{name}'))
    return items


def cache_path(url):
    path = urllib.parse.urlparse(url).path
    ext = os.path.splitext(path)[1] or '.bin'
    return os.path.join(CACHE, hashlib.sha1(url.encode()).hexdigest()[:16] + ext)


def cached(url):
    path = cache_path(url)
    return os.path.exists(path) and os.path.getsize(path) > 2000


def obtain(url):
    os.makedirs(CACHE, exist_ok=True)
    path = cache_path(url)
    if cached(url):
        return path, False
    raw = fetch(url)
    if raw[:4] not in (b'OggS', b'RIFF', b'ID3\x03', b'\xff\xfb'):
        raise RuntimeError(f'not audio ({raw[:4]!r})')
    with open(path, 'wb') as fh:
        fh.write(raw)
    return path, True


# --- pages ------------------------------------------------------------------
MOK_DOI = 'https://doi.org/10.1017/S0954394513000161'
MOK_API = 'https://api.crossref.org/works/10.1017/s0954394513000161'
WIKI_MANDARIN = 'https://en.wikipedia.org/wiki/Standard_Chinese_phonology'
WIKI_CANTONESE = 'https://en.wikipedia.org/wiki/Cantonese_phonology'

PAGES = [
    {
        'key': 'mandarin-chao-values',
        'option': 'Standard Chinese phonology (Wikipedia)',
        'property': 'Mandarin tones 1 to 4 in Chao values',
        'value': '55, 35, 21(4), 51',
        'url': WIKI_MANDARIN,
        'quote': '˥ 55 ˧˥ 35 ˨˩˦ 21(4) ˥˩ 51',
    },
    {
        'key': 'mandarin-tone3-214',
        'option': 'Standard Chinese phonology (Wikipedia)',
        'property': 'Mandarin tone 3 written as 214',
        'value': '214',
        'url': WIKI_MANDARIN,
        'quote': 'traditionally described as ˨˩˦ 214',
    },
    {
        'key': 'cantonese-tone-letters',
        'option': 'Cantonese phonology (Wikipedia)',
        'property': 'Cantonese tones 1 to 6 on si, in tone letters',
        'value': '55 or 53, 35, 33, 21 or 11, 13, 22',
        'url': WIKI_CANTONESE,
        'quote': 'siː˥ , siː˥˧ siː˧˥ siː˧ siː˨˩ , siː˩ siː˩˧ siː˨',
    },
    {
        'key': 'cantonese-descriptions',
        'option': 'Cantonese phonology (Wikipedia)',
        'property': 'Cantonese tones 1 to 6 described',
        'value': 'high level; medium rising; medium level; low falling; low rising; low level',
        'url': WIKI_CANTONESE,
        'quote': ('high level, high falling medium rising medium level low falling, very low '
                  'level low rising low level'),
    },
    {
        'key': 'mok-merging-pairs',
        'option': 'Mok, Zuo and Wong 2013',
        'property': 'tone pairs that appear to be merging, with Chao values',
        'value': 'T2 25 vs T5 23, T3 33 vs T6 22, T4 21 vs T6 22',
        'url': MOK_API,
        'cite': MOK_DOI,
        'quote': ('some tone pairs appear to be merging: T2 [25] vs. T5 [23], T3 [33] vs. '
                  'T6 [22], and T4 [21] vs. T6 [22]'),
    },
    {
        'key': 'mok-participants',
        'option': 'Mok, Zuo and Wong 2013',
        'property': 'participants',
        'value': '28 merging, 30 control, Hong Kong',
        'url': MOK_API,
        'cite': MOK_DOI,
        'quote': ('Twenty-eight merging participants and thirty control participants in Hong '
                  'Kong were recruited for a perception experiment'),
    },
    {
        'key': 'mok-six-categories',
        'option': 'Mok, Zuo and Wong 2013',
        'property': 'production of the merging group',
        'value': 'still six tone categories, reduced tone space',
        'url': MOK_API,
        'cite': MOK_DOI,
        'quote': 'the merging participants still had six tone categories in production',
    },
    {
        'key': 'mok-slower',
        'option': 'Mok, Zuo and Wong 2013',
        'property': 'perception of the merging group',
        'value': 'significantly slower than the control group',
        'url': MOK_API,
        'cite': MOK_DOI,
        'quote': ('The merging group was significantly slower in tone perception than the '
                  'control group was.'),
    },
    {
        'key': 'pleco-display',
        'option': 'Pleco',
        'property': 'shows a Cantonese reading next to the Mandarin one',
        'value': 'yes, in curly brackets after the Pinyin, when Cantonese display is on',
        'url': 'https://www.pleco.com/manual/ios/dict/',
        'quote': ("If you’ve enabled Cantonese display, the Cantonese romanization "
                  "for the word will appear in curly brackets {} after the Pinyin."),
    },
    {
        'key': 'pleco-jyutping',
        'option': 'Pleco',
        'property': 'Cantonese search romanisation',
        'value': 'Jyutping or Yale',
        'url': 'https://www.pleco.com/manual/ios/dict/',
        'quote': ('Pleco will also accept search inputs in Jyutping- or Yale- '
                  'romanized Cantonese'),
    },
    {
        'key': 'wordshk-crowdsourced',
        'option': 'words.hk',
        'property': 'how it is built',
        'value': 'crowd-sourced Cantonese dictionary',
        'url': 'https://cantowords.com/base/about/',
        'quote': ('We use crowd-sourcing methods to sustainably develop a comprehensive '
                  'Cantonese dictionary'),
    },
    {
        'key': 'wordshk-hong-kong',
        'option': 'words.hk',
        'property': 'which Cantonese it documents',
        'value': 'contemporary Hong Kong Cantonese',
        'url': 'https://cantowords.com/base/about/',
        'quote': ('our goal is to document the actual contemporary state of the Cantonese '
                  'language in Hong Kong'),
    },
    {
        'key': 'wordshk-audio',
        'option': 'words.hk',
        'property': 'audio on entry pages',
        'value': 'one audio file per Jyutping syllable',
        'url': 'https://words.hk/zidin/%E7%B9%91',
        'quote': 'var url = "/static/jyutping/" + jp + ext;',
        'raw': True,
    },
    {
        'key': 'wordshk-licence',
        'option': 'words.hk',
        'property': 'licence of the entries',
        'value': 'non-commercial open data licence 1.0',
        'url': 'https://words.hk/zidin/%E7%B9%91',
        'quote': '非商業開放資料授權協議 1.0',
    },
    {
        'key': 'anki-flashcards',
        'option': 'Anki',
        'property': 'build your own deck',
        'value': 'yes',
        'url': 'https://apps.ankiweb.net/',
        'quote': 'Create a new deck and add some flashcards to get started.',
    },
    {
        'key': 'anki-media',
        'option': 'Anki',
        'property': 'audio on cards',
        'value': 'yes',
        'url': 'https://apps.ankiweb.net/',
        'quote': 'Audio, images, videos, and scientific markup can be used in your flashcards.',
    },
]


def check_pages():
    results, ok, cache = [], True, {}
    for p in PAGES:
        row = dict(p)
        try:
            if p['url'] not in cache:
                cache[p['url']] = fetch(p['url'])
            body = cache[p['url']]
            text = normalise(body.decode('utf-8', 'replace')) if p.get('raw') else page_text(body)
            row['found'] = quote_present(text, p['quote'])
        except Exception as exc:
            row['found'] = False
            row['error'] = str(exc)
        ok = ok and row['found']
        results.append(row)
    return results, ok


# --- licences ---------------------------------------------------------------
def check_licences():
    """Licence and uploader of every recording, read from the Commons API."""
    titles = {}
    for key, speaker, url in corpus():
        titles['File:' + urllib.parse.unquote(url.rsplit('/', 1)[1])] = key
    found = {}
    names = list(titles)
    for i in range(0, len(names), 40):
        q = urllib.parse.urlencode({
            'action': 'query', 'format': 'json', 'prop': 'imageinfo',
            'iiprop': 'extmetadata|user', 'titles': '|'.join(names[i:i + 40])})
        data = json.loads(fetch('https://commons.wikimedia.org/w/api.php?' + q))
        norm = {n['to']: n['from'] for n in data['query'].get('normalized', [])}
        for page in data['query']['pages'].values():
            title = norm.get(page['title'], page['title'])
            info = (page.get('imageinfo') or [{}])[0]
            meta = info.get('extmetadata', {})
            found[titles.get(title, title)] = {
                'licence': meta.get('LicenseShortName', {}).get('value'),
                'uploader': info.get('user'),
            }
    return found


# --- product claims ---------------------------------------------------------
def check_product():
    """Re-count what the post says about Tingyin itself, from the repository this file is in."""
    manifest = os.path.join(REPO, 'fixtures', 'audio-manifest.json')
    if not os.path.exists(manifest):
        return [{'key': 'repo', 'skipped': 'not run inside the Tingyin repository'}], True
    rows, ok = [], True
    with open(manifest) as fh:
        entries = json.load(fh)
    counts = {
        'manifest-entries': (len(entries), 637),
        'manifest-cc-by-sa': (sum(1 for e in entries if e.get('license') == 'CC BY-SA 4.0'), 622),
        'manifest-cc0': (sum(1 for e in entries if e.get('license') == 'CC0'), 15),
    }
    for key, (got, expected) in counts.items():
        rows.append({'key': key, 'expected': expected, 'got': got, 'ok': got == expected})
        ok = ok and got == expected
    fields = {'source', 'speaker', 'license', 'sha256'}
    complete = all(fields <= set(e) for e in entries)
    rows.append({'key': 'manifest-fields', 'expected': sorted(fields),
                 'got': 'every entry has them' if complete else 'missing on some entry',
                 'ok': complete})
    ok = ok and complete
    try:
        with open(os.path.join(REPO, 'apps', 'api', 'src', 'corpus', 'entitlement.ts')) as fh:
            ent = fh.read()
        levels_ok = ('PUBLIC_MAX_LEVEL = 1' in ent
                     and 'Level 2 is free only to a signed-in account' in ent)
    except OSError:
        levels_ok = False
    rows.append({'key': 'levels-1-2-free', 'expected': 'level 1 anonymous, level 2 signed in',
                 'got': 'entitlement.ts agrees' if levels_ok else 'not found', 'ok': levels_ok})
    ok = ok and levels_ok
    grep = subprocess.run(['git', '-C', REPO, 'grep', '-il', 'cantonese', '--',
                           'apps/web/src', 'apps/api/src', 'packages/shared/src'],
                          capture_output=True).stdout.decode().strip()
    hits = [l for l in grep.splitlines() if '/blog/' not in l]
    rows.append({'key': 'no-cantonese-material', 'expected': 'no non-blog source mentions Cantonese',
                 'got': hits or 'none', 'ok': not hits})
    ok = ok and not hits
    return rows, ok


# --- dataset ----------------------------------------------------------------
def build_inputs(licences):
    inputs = [{'kind': 'page', 'url': u, 'used_for': 'quote check'}
              for u in sorted({p['url'] for p in PAGES})]
    inputs.append({'kind': 'api', 'url': 'https://commons.wikimedia.org/w/api.php',
                   'used_for': 'licence and uploader of every recording'})
    for key, speaker, url in corpus():
        path = cache_path(url)
        digest = None
        if os.path.exists(path):
            with open(path, 'rb') as fh:
                digest = hashlib.sha256(fh.read()).hexdigest()
        lic = licences.get(key) or {}
        inputs.append({'kind': 'audio', 'key': key, 'speaker': speaker, 'url': url,
                       'licence': lic.get('licence'), 'sha256': digest})
    for path in ('fixtures/audio-manifest.json', 'apps/api/src/corpus/entitlement.ts'):
        inputs.append({'kind': 'repo', 'url': path})
    return inputs


def build_lab(vals, licences, np):
    sets = []
    for syl in ('chaang', 'cho', 'faan', 'fu'):
        try:
            t1, t3, t6 = (vals[f'{syl}{t}']['median_hz'] for t in (1, 3, 6))
        except (KeyError, TypeError):
            continue
        sets.append({
            'syllable': syl,
            'tone1_hz': t1, 'tone3_hz': t3, 'tone6_hz': t6,
            'tone1_tone3_st': round(st(t1, t3), 2),
            'tone3_tone6_st': round(st(t3, t6), 2),
            'tone1_tone6_st': round(st(t1, t6), 2),
            'sd_tone1_hz': vals[f'{syl}1']['sd_hz'],
            'sd_tone3_hz': vals[f'{syl}3']['sd_hz'],
            'sd_tone6_hz': vals[f'{syl}6']['sd_hz'],
        })
    by_speaker, lic_by_speaker = {}, {}
    for key, speaker, url in corpus():
        if vals.get(key):
            by_speaker.setdefault(speaker, []).append(vals[key]['median_hz'])
        lic = (licences.get(key) or {}).get('licence')
        if lic:
            lic_by_speaker.setdefault(speaker, set()).add(lic)
    rows = [{'speaker': sp, 'files': len(v),
             'median_hz': round(float(np.median(np.array(v))), 1),
             'licences': ', '.join(sorted(lic_by_speaker.get(sp, [])))}
            for sp, v in by_speaker.items()]
    rows.sort(key=lambda r: r['median_hz'])
    span = round(st(rows[-1]['median_hz'], rows[0]['median_hz']), 2) if len(rows) > 1 else None
    return {
        'within_speaker': {
            'what': ('Median F0 over the middle 60 % of the voiced part of Cantonese tones 1, 3 '
                     'and 6, the level tones, for four syllables recorded by one speaker '
                     '(Jyugulik, Wikimedia Commons, CC BY-SA 4.0)'),
            'sets': sets,
        },
        'across_speakers': {
            'what': ('Median of the per-recording median F0 for each speaker over their '
                     'sampled recordings; the span is the distance from the lowest to the '
                     'highest speaker'),
            'speakers': rows,
            'span_st': span,
        },
    }


METHOD = ('public-corpus: pitch of Cantonese tones 1, 3 and 6 measured with ffmpeg and numpy '
          'on CC-licensed Cantonese recordings from Wikimedia Commons; primary-docs for Pleco, '
          'words.hk and Anki; the Chao values and the tone-merging study read from their pages')
TOOLS = [
    'ffmpeg 8.0.1', 'Python 3.9.6', 'numpy 1.26.4',
    'urllib with a descriptive User-Agent', 'Wikimedia Commons API (action=query, imageinfo)',
    'Crossref REST API (abstract of doi:10.1017/S0954394513000161)',
]
NOTES = [
    'No child is recorded in the corpus, so the earlier wording that a child and an adult '
    'differ by more than the three tones was not tested; every speaker measured is an adult, '
    'and the post now compares adult speakers only.',
    'The five-speaker span (9.05 semitones) is about the same as tone 1 to tone 6 inside one '
    'voice (7.92 to 9.71), not larger; it is larger than any adjacent pair (2.67 to 5.79).',
    'The across-speaker figure compares each speaker’s median over a varied sample '
    '(six tones over four syllables for Jyugulik, ordinary words for the other four '
    'speakers), not the same syllable across speakers: no syllable in this Commons set '
    'is recorded by more than one person.',
    'Speakers are identified only by their Commons uploader name; nothing in the corpus '
    'states age or sex, so no such grouping was used. One Fête file is uploaded as '
    '“Fête Phung” with the author field “Fête”.',
    'Cantonese tone labels come from the Commons file names, which give the Jyutping tone '
    'digit for each Jyugulik file.',
    'Only the middle 60 % of each voiced run is measured. The first and last fifth of these '
    'recordings carries octave errors from onset noise and creak, so no contour is reported; '
    'the within-recording spread of tones 1, 3 and 6 (0.9 to 13.9 Hz standard deviation) is '
    'what shows they do not move.',
    'Yue-cho4.ogg has too few measurable voiced frames (7 against a floor of 8) and is not '
    'used; cho has no tone 4 row as a result, which does not touch the level-tone table.',
    'Pleco: the manual names the display only as a Cantonese romanisation and names Jyutping '
    'and Yale for search, so the post no longer says the display is in Jyutping.',
    'words.hk: the entry page builds its player from /static/jyutping/<syllable>.mp3; that '
    'proves audio per syllable, not who recorded it, so the post does not call it a human '
    'or Hong Kong speaker recording.',
    'The Mok, Zuo and Wong (2013) statements are read from the abstract served by Crossref; '
    'the full paper is behind the publisher’s paywall and was not read. The abstract '
    'does not say the merging speakers are younger, so the post no longer says so.',
    'Wikipedia pages change; check.py re-reads the exact tone-letter strings and fails when '
    'they are gone.',
    'Not checked: that Cantonese tone change is lexical rather than an automatic rule, the '
    'Middle Chinese correspondence, and the claim that Mandarin tones do not flatten in fast '
    'speech (that one is measured in the post it links to).',
]


def write_csv(pages, lab):
    fields = ['section', 'item', 'property', 'value', 'tone1_hz', 'tone3_hz', 'tone6_hz',
              'tone1_tone3_st', 'tone3_tone6_st', 'tone1_tone6_st', 'sd_tone1_3_6_hz',
              'recordings', 'median_hz', 'licence', 'url']
    rows = []
    for s in lab['within_speaker']['sets']:
        rows.append({
            'section': 'level tones, one speaker', 'item': s['syllable'],
            'tone1_hz': s['tone1_hz'], 'tone3_hz': s['tone3_hz'], 'tone6_hz': s['tone6_hz'],
            'tone1_tone3_st': s['tone1_tone3_st'], 'tone3_tone6_st': s['tone3_tone6_st'],
            'tone1_tone6_st': s['tone1_tone6_st'],
            'sd_tone1_3_6_hz': '%.1f / %.1f / %.1f' % (
                s['sd_tone1_hz'], s['sd_tone3_hz'], s['sd_tone6_hz']),
            'recordings': 3, 'licence': 'CC BY-SA 4.0',
            'url': 'https://commons.wikimedia.org/wiki/File:Yue-%s1.ogg' % s['syllable'],
        })
    for sp in lab['across_speakers']['speakers']:
        rows.append({'section': 'typical pitch, across speakers', 'item': sp['speaker'],
                     'recordings': sp['files'], 'median_hz': sp['median_hz'],
                     'licence': sp['licences']})
    rows.append({'section': 'typical pitch, across speakers', 'item': 'lowest to highest speaker',
                 'property': 'span (semitones)', 'value': lab['across_speakers']['span_st']})
    for p in pages:
        rows.append({'section': 'sources', 'item': p['option'], 'property': p['property'],
                     'value': p['value'], 'url': p.get('cite', p['url'])})
    with open(CSV_PATH, 'w', newline='') as fh:
        w = csv.DictWriter(fh, fieldnames=fields)
        w.writeheader()
        w.writerows(rows)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--recheck', action='store_true',
                    help='re-read pages and licences; measure only from cached audio')
    ap.add_argument('--record', action='store_true',
                    help='recompute and write dataset.json and dataset.csv')
    args = ap.parse_args()
    np = __import__('numpy')
    expected = None
    if not args.record:
        with open(DATASET) as fh:
            expected = json.load(fh)

    print('== pages')
    page_results, pages_ok = check_pages()
    for r in page_results:
        print(f"  [{'ok' if r['found'] else 'MISSING'}] {r['key']}  {r['url']}")
        if 'error' in r:
            print(f'      error: {r["error"]}')

    print('== licences')
    licences_ok = True
    try:
        licences = check_licences()
    except Exception as exc:
        licences, licences_ok = {}, False
        print(f'  [FAIL] Commons API: {exc}')
    if expected:
        want = {i['key']: i['licence'] for i in expected['inputs'] if i['kind'] == 'audio'}
        for key, lic in want.items():
            got = (licences.get(key) or {}).get('licence')
            if got != lic:
                print(f'  [FAIL] {key}: {got} != {lic}')
                licences_ok = False
    print(f'  {sum(1 for v in licences.values() if v.get("licence"))} recordings with a licence, '
          + ', '.join(sorted({v["licence"] for v in licences.values() if v.get("licence")})))

    print('== lab')
    items = corpus()
    lab_ok, lab = True, None
    if args.recheck and not all(cached(url) for _, _, url in items):
        print(f'  skipped under --recheck: audio not cached in {CACHE}; '
              'run without --recheck to download about 4 MB and re-measure')
    else:
        vals, fresh, skipped = {}, 0, 0
        for key, speaker, url in items:
            try:
                path, new = obtain(url)
                fresh += new
                vals[key] = analyse(path)
            except Exception as exc:
                vals[key] = None
                skipped += 1
                print(f'  [SKIP] {key}: {exc}')
        print(f'  {len(vals)} recordings, {fresh} downloaded, {skipped} not measurable')
        lab = build_lab(vals, licences, np)
        for s in lab['within_speaker']['sets']:
            print(f"  {s['syllable']}: {s['tone1_hz']}/{s['tone3_hz']}/{s['tone6_hz']} Hz, "
                  f"gaps {s['tone1_tone3_st']}/{s['tone3_tone6_st']} st, "
                  f"tone1-tone6 {s['tone1_tone6_st']} st")
        for r in lab['across_speakers']['speakers']:
            print(f"  {r['speaker']}: {r['median_hz']} Hz over {r['files']} files")
        print(f"  speaker span: {lab['across_speakers']['span_st']} st")

    print('== product claims')
    product_rows, product_ok = check_product()
    for r in product_rows:
        state = 'ok' if r.get('ok') else ('skipped' if 'skipped' in r else 'MISMATCH')
        print(f"  [{state}] {r['key']}: {r.get('got', r.get('skipped', ''))}")

    if args.record:
        if lab is None:
            print('  --record needs the lab step; run without --recheck')
            return 1
        sources = [{k: r[k] for k in ('key', 'option', 'property', 'value', 'url', 'quote')}
                   for r in page_results]
        for s, r in zip(sources, page_results):
            if r.get('cite'):
                s['cite'] = r['cite']
            s['found'] = r['found']
        dataset = {
            'method': METHOD,
            'checkedAt': CHECKED_AT,
            'tools': TOOLS,
            'inputs': build_inputs(licences),
            'results': {
                'sources': sources,
                'lab': lab,
                'product': product_rows,
            },
            'notes': NOTES,
        }
        with open(DATASET, 'w') as fh:
            json.dump(dataset, fh, ensure_ascii=False, indent=1)
            fh.write('\n')
        write_csv(page_results, lab)
        print('  dataset.json and dataset.csv written')
        return 0 if (pages_ok and licences_ok and product_ok) else 1

    def close(a, b, tol):
        return a is not None and b is not None and abs(a - b) <= tol

    if lab is not None:
        exp_lab = expected['results']['lab']
        for exp in exp_lab['within_speaker']['sets']:
            got = next((s for s in lab['within_speaker']['sets']
                        if s['syllable'] == exp['syllable']), None)
            if got is None:
                print(f"  [FAIL] {exp['syllable']}: not measured")
                lab_ok = False
                continue
            for field in ('tone1_hz', 'tone3_hz', 'tone6_hz'):
                if not close(got[field], exp[field], max(2.0, 0.02 * exp[field])):
                    print(f"  [FAIL] {exp['syllable']} {field}: {got[field]} != {exp[field]}")
                    lab_ok = False
            for field in ('tone1_tone3_st', 'tone3_tone6_st', 'tone1_tone6_st'):
                if not close(got[field], exp[field], 0.15):
                    print(f"  [FAIL] {exp['syllable']} {field}: {got[field]} != {exp[field]}")
                    lab_ok = False
        for exp in exp_lab['across_speakers']['speakers']:
            got = next((r for r in lab['across_speakers']['speakers']
                        if r['speaker'] == exp['speaker']), None)
            if got is None or not close(got['median_hz'], exp['median_hz'],
                                        max(2.0, 0.02 * exp['median_hz'])):
                print(f"  [FAIL] {exp['speaker']}: {got and got['median_hz']} != {exp['median_hz']}")
                lab_ok = False
        if not close(lab['across_speakers']['span_st'], exp_lab['across_speakers']['span_st'], 0.15):
            print(f"  [FAIL] span: {lab['across_speakers']['span_st']} != "
                  f"{exp_lab['across_speakers']['span_st']}")
            lab_ok = False

    print('== verdict')
    print(f'  pages {"ok" if pages_ok else "FAILED"}, '
          f'licences {"ok" if licences_ok else "FAILED"}, '
          f'lab {"skipped" if lab is None else ("ok" if lab_ok else "FAILED")}, '
          f'product {"ok" if product_ok else "FAILED"}')
    return 0 if (pages_ok and licences_ok and lab_ok and product_ok) else 1


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