#!/usr/bin/env python3
"""Re-runs the check behind the how-many-mandarin-syllables post.

The measurement (public-corpus) parses CC-CEDICT, counts how many of the 409
syllables in Tingyin's pinyin table occur in each tone, and cross-checks the
table against the syllable set the dictionary actually uses. The verification
half re-reads the two vendor pages the post names and re-derives every number
from the product's own files and live endpoints.

    python3 check.py             # verify dataset.json against the live sources
    python3 check.py --recheck   # same; there is no lab step to skip
    python3 check.py --build     # rebuild dataset.json and dataset.csv

On a CC-CEDICT edition newer than the one measured, the entry count is reported
rather than failed: the post dates that count to the 26 October 2026 edition.
Every other value derived from the dictionary still has to match exactly.

Standard library only. Set TINGYIN_REPO if the repository is not five
directories above this file.
"""

import argparse
import csv
import gzip
import hashlib
import html
import json
import os
import re
import subprocess
import sys
import urllib.request

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

REPO = os.environ.get('TINGYIN_REPO') or os.path.abspath(
    os.path.join(HERE, '..', '..', '..', '..', '..')
)
REV = 'HEAD'

CEDICT_URL = 'https://www.mdbg.net/chinese/export/cedict/cedict_1_0_ts_utf-8_mdbg.txt.gz'
CHART_URL = 'https://www.tingyin.app/pinyin-chart'
API_LEVEL1 = 'https://api.tingyin.app/corpus?level=1'
PURPLE_URL = 'https://www.purpleculture.net/chinese-pinyin-chart/'
YOYO_URL = 'https://yoyochinese.com/chinese-learning-tools/Mandarin-Chinese-pronunciation-lesson/pinyin-chart-table'

TABLE_SRC = REV + ':apps/web/src/lib/pinyin/table.ts'
MANIFEST_SRC = REV + ':fixtures/audio-manifest.json'

UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36'

PURPLE_QUOTE = (
    'This Pinyin chart includes all valid Mandarin Chinese syllables. Mouseover on any '
    'pinyin cell in the chart to listen to the audio in all four tones and view sample words.'
)
YOYO_QUOTE = (
    'Learn how to pronounce Mandarin Chinese like a native by practicing with our audio '
    'demonstrations and video explanations for every possible sound combination in the language.'
)
YOYO_409_QUOTE = (
    'Once you master these 409 sounds along with the tones, you\'ll have practically mastered '
    'the pronunciation of every single word in the Chinese language.'
)

TONE_MAP = {
    'ā': 'a', 'á': 'a', 'ǎ': 'a', 'à': 'a',
    'ē': 'e', 'é': 'e', 'ě': 'e', 'è': 'e',
    'ī': 'i', 'í': 'i', 'ǐ': 'i', 'ì': 'i',
    'ō': 'o', 'ó': 'o', 'ǒ': 'o', 'ò': 'o',
    'ū': 'u', 'ú': 'u', 'ǔ': 'u', 'ù': 'u',
    'ǖ': 'ü', 'ǘ': 'ü', 'ǚ': 'ü', 'ǜ': 'ü',
}

CEDICT_TOKEN = re.compile(r'^([a-zA-Zü:ê]+?)([1-5])$')


# ---------------------------------------------------------------- text and fetching

def norm_text(s):
    s = html.unescape(s)
    for a, b in (('’', "'"), ('‘', "'"), ('“', '"'), ('”', '"'),
                 ('—', '-'), ('–', '-'), (' ', ' ')):
        s = s.replace(a, b)
    return re.sub(r'\s+', ' ', s).strip()


def html_to_text(s):
    s = re.sub(r'<(script|style)[^>]*>.*?</\1>', ' ', s, flags=re.S | re.I)
    s = re.sub(r'<[^>]+>', ' ', s)
    return norm_text(s)


def http_get(url, timeout=120):
    req = urllib.request.Request(url, headers={'User-Agent': UA,
                                               'Accept-Language': 'en-US,en;q=0.9'})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return r.read(), r.status


def read_repo_file(path):
    try:
        out = subprocess.run(['git', '-C', REPO, 'show', f'{REV}:{path}'],
                             capture_output=True, check=True)
        return out.stdout.decode('utf-8')
    except (subprocess.CalledProcessError, FileNotFoundError):
        with open(os.path.join(REPO, path), encoding='utf-8') as f:
            return f.read()


def strip_tones(pinyin):
    return ''.join(TONE_MAP.get(c, c) for c in pinyin).lower().replace('v', 'ü')


def read_table(src):
    block = src.split('export const SYLLABLE_TABLE')[1].split('export const SYLLABLE_COUNT')[0]
    cells, per_initial, per_final = [], {}, {}
    for m in re.finditer(r"^\s*'?([a-z∅]+)'?\s*:\s*\{([^}]*)\}", block, re.M):
        initial, body = m.group(1), m.group(2)
        spellings = re.findall(r"[a-zü:]+:\s*'([^']+)'", body)
        per_initial[initial] = len(spellings)
        cells.extend(spellings)
        for final in re.findall(r"([a-zü:]+):\s*'", body):
            per_final[final] = per_final.get(final, 0) + 1
    return cells, per_initial, per_final


def cedict_syllables(text):
    syl = {}
    for line in text.splitlines():
        if line.startswith('#'):
            continue
        m = re.search(r'\[([^\]]*)\]', line)
        if not m:
            continue
        for tok in m.group(1).split():
            low = tok.lower()
            if low in ('r5', 'r'):
                continue
            mm = CEDICT_TOKEN.match(low)
            if not mm:
                continue
            base = mm.group(1).replace('u:', 'ü').replace('v', 'ü').replace('ê', 'e')
            syl.setdefault(base, set()).add(mm.group(2))
    return syl


def cedict_entries_using(text, target):
    n = 0
    for line in text.splitlines():
        if line.startswith('#'):
            continue
        m = re.search(r'\[([^\]]*)\]', line)
        if not m:
            continue
        for tok in m.group(1).split():
            mm = CEDICT_TOKEN.match(tok.lower())
            if mm and mm.group(1).replace('u:', 'ü').replace('v', 'ü').replace('ê', 'e') == target:
                n += 1
                break
    return n


# ---------------------------------------------------------------- the measurement

def analyse(cache):
    out = {}

    table_src = cache.setdefault('table', read_repo_file('apps/web/src/lib/pinyin/table.ts'))
    cells, per_initial, per_final = read_table(table_src)
    cellset = set(cells)
    finals = len(per_final)
    out['table.cells'] = len(cells)
    out['table.distinct_spellings'] = len(cellset)
    out['table.initials'] = len(per_initial)
    out['table.finals'] = finals
    out['table.empty_cells'] = len(per_initial) * finals - len(cells)
    for init in ('f', 'j', 'q', 'x', 'l'):
        out[f'table.{init}_finals'] = per_initial.get(init)
    out['table.zero_finals'] = per_initial.get('∅')
    out['table.once_finals'] = ','.join(sorted(f for f, c in per_final.items() if c == 1))

    manifest = json.loads(cache.setdefault('manifest', read_repo_file('fixtures/audio-manifest.json')))
    out['manifest.entries'] = len(manifest)
    out['manifest.cc_by_sa'] = sum(1 for e in manifest if e.get('license') == 'CC BY-SA 4.0')
    out['manifest.cc0'] = sum(1 for e in manifest if e.get('license') == 'CC0')
    single = [e for e in manifest if e.get('syllableCount') == 1]
    out['manifest.single_bases'] = len({strip_tones(e['pinyin']) for e in single})

    api = json.loads(cache.setdefault('api', http_get(API_LEVEL1)[0]))['data']
    api_single = [x for x in api if x.get('syllableCount') == 1]
    out['api.l1_items'] = len(api)
    out['api.l1_single_bases'] = len({strip_tones(x['citationPinyin']) for x in api_single})

    chart_html = cache.setdefault('chart', http_get(CHART_URL)[0]).decode('utf-8', 'replace')
    out['chart.summary_cells'] = len(re.findall(r'<summary', chart_html))

    gz = cache.setdefault('cedict_gz', http_get(CEDICT_URL)[0])
    text = gzip.decompress(gz).decode('utf-8')
    cache['cedict_sha256_gz'] = hashlib.sha256(gz).hexdigest()
    cache['cedict_sha256_txt'] = hashlib.sha256(text.encode('utf-8')).hexdigest()
    cache['cedict_header_entries'] = int(text.split('entries=', 1)[1].split('\n', 1)[0])
    mdate = re.search(r'^#! date=(\S+)', text, re.M)
    cache['cedict_header_date'] = mdate.group(1) if mdate else None

    syl = cedict_syllables(text)
    out['cedict.entries'] = cache['cedict_header_entries']
    out['cedict.distinct_bases'] = len(syl)
    out['cedict.distinct_toned'] = len({(b, t) for b, ts in syl.items() for t in ts})
    out['cedict.toned_within_table'] = len({(b, t) for b in cellset for t in syl.get(b, set())})
    out['cedict.toned_tones_1_4'] = len({(b, t) for b, ts in syl.items() for t in ts if t in '1234'})
    counts = {b: len(syl.get(b, set()) & {'1', '2', '3', '4'}) for b in cellset}
    out['cedict.syllables_in_4_tones'] = sum(1 for n in counts.values() if n == 4)
    out['cedict.syllables_in_3_tones'] = sum(1 for n in counts.values() if n == 3)
    out['cedict.syllables_in_2_tones'] = sum(1 for n in counts.values() if n == 2)
    out['cedict.syllables_in_1_tone'] = sum(1 for n in counts.values() if n == 1)
    out['cedict.syllables_in_0_tones'] = sum(1 for n in counts.values() if n == 0)
    out['cedict.neutral_only_bases'] = ', '.join(sorted(b for b in cellset if counts[b] == 0))
    out['cedict.with_neutral'] = sum(1 for b in cellset if '5' in syl.get(b, set()))
    extra = sorted(set(syl) - cellset)
    out['cedict.bases_not_in_table'] = len(extra)
    out['cedict.bases_missing_from_cedict'] = len(cellset - set(syl))
    out['cedict.weng_entries'] = cedict_entries_using(text, 'weng')
    cache['cedict_extra_bases'] = extra

    for key, url, quote in (('purple', PURPLE_URL, PURPLE_QUOTE), ('yoyo', YOYO_URL, YOYO_QUOTE),
                            ('yoyo409', YOYO_URL, YOYO_409_QUOTE)):
        page = cache.setdefault(key, http_get(url)[0]).decode('utf-8', 'replace')
        out[f'{key}.quote_present'] = norm_text(quote) in html_to_text(page)

    return out


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

def rows(spec):
    def v(key):
        return spec[key]

    r = [
        ('table.cells', 'Tingyin pinyin table', 'valid initial-final cells', v('table.cells'), TABLE_SRC, None),
        ('table.distinct_spellings', 'Tingyin pinyin table', 'distinct spellings', v('table.distinct_spellings'), TABLE_SRC, None),
        ('table.initials', 'Tingyin pinyin table', 'initial rows (21 initials plus zero)', v('table.initials'), TABLE_SRC, None),
        ('table.finals', 'Tingyin pinyin table', 'finals', v('table.finals'), TABLE_SRC, None),
        ('table.empty_cells', 'Tingyin pinyin table', 'empty cells in the 22 x 35 grid', v('table.empty_cells'), TABLE_SRC, None),
        ('table.f_finals', 'Tingyin pinyin table', 'finals taken by f', v('table.f_finals'), TABLE_SRC, None),
        ('table.j_finals', 'Tingyin pinyin table', 'finals taken by j', v('table.j_finals'), TABLE_SRC, None),
        ('table.q_finals', 'Tingyin pinyin table', 'finals taken by q', v('table.q_finals'), TABLE_SRC, None),
        ('table.x_finals', 'Tingyin pinyin table', 'finals taken by x', v('table.x_finals'), TABLE_SRC, None),
        ('table.l_finals', 'Tingyin pinyin table', 'finals taken by l', v('table.l_finals'), TABLE_SRC, None),
        ('table.zero_finals', 'Tingyin pinyin table', 'finals taken by the zero initial', v('table.zero_finals'), TABLE_SRC, None),
        ('table.once_finals', 'Tingyin pinyin table', 'finals appearing in exactly one cell', v('table.once_finals'), TABLE_SRC, None),

        ('manifest.entries', 'Tingyin audio manifest', 'entries', v('manifest.entries'), MANIFEST_SRC, None),
        ('manifest.cc_by_sa', 'Tingyin audio manifest', 'entries licensed CC BY-SA 4.0', v('manifest.cc_by_sa'), MANIFEST_SRC, None),
        ('manifest.cc0', 'Tingyin audio manifest', 'entries licensed CC0', v('manifest.cc0'), MANIFEST_SRC, None),
        ('manifest.single_bases', 'Tingyin audio manifest', 'distinct syllables with a single-syllable recording', v('manifest.single_bases'), MANIFEST_SRC, None),

        ('api.l1_items', 'Tingyin API /corpus?level=1', 'items returned signed out', v('api.l1_items'), API_LEVEL1, None),
        ('api.l1_single_bases', 'Tingyin API /corpus?level=1', 'distinct syllables playable signed out', v('api.l1_single_bases'), API_LEVEL1, None),

        ('chart.summary_cells', 'tingyin.app/pinyin-chart', 'syllable cells in the served HTML', v('chart.summary_cells'), CHART_URL, None),

        ('cedict.entries', 'CC-CEDICT', 'entries in the edition read', v('cedict.entries'), CEDICT_URL, None),
        ('cedict.distinct_bases', 'CC-CEDICT', 'distinct toneless syllables the dictionary uses', v('cedict.distinct_bases'), CEDICT_URL, None),
        ('cedict.distinct_toned', 'CC-CEDICT', 'distinct toned syllables in the dictionary', v('cedict.distinct_toned'), CEDICT_URL, None),
        ('cedict.toned_within_table', 'CC-CEDICT', 'distinct toned syllables among the 409', v('cedict.toned_within_table'), CEDICT_URL, None),
        ('cedict.toned_tones_1_4', 'CC-CEDICT', 'distinct toned syllables counting tones 1-4 only', v('cedict.toned_tones_1_4'), CEDICT_URL, None),
        ('cedict.syllables_in_4_tones', 'CC-CEDICT', 'of the 409 syllables used in all four of tones 1-4', v('cedict.syllables_in_4_tones'), CEDICT_URL, None),
        ('cedict.syllables_in_3_tones', 'CC-CEDICT', 'of the 409 syllables used in exactly three of tones 1-4', v('cedict.syllables_in_3_tones'), CEDICT_URL, None),
        ('cedict.syllables_in_2_tones', 'CC-CEDICT', 'of the 409 syllables used in exactly two of tones 1-4', v('cedict.syllables_in_2_tones'), CEDICT_URL, None),
        ('cedict.syllables_in_1_tone', 'CC-CEDICT', 'of the 409 syllables used in exactly one of tones 1-4', v('cedict.syllables_in_1_tone'), CEDICT_URL, None),
        ('cedict.syllables_in_0_tones', 'CC-CEDICT', 'of the 409 syllables used in none of tones 1-4', v('cedict.syllables_in_0_tones'), CEDICT_URL, None),
        ('cedict.neutral_only_bases', 'CC-CEDICT', 'the syllables used in none of tones 1-4', v('cedict.neutral_only_bases'), CEDICT_URL, None),
        ('cedict.with_neutral', 'CC-CEDICT', 'of the 409 syllables with a neutral-tone reading', v('cedict.with_neutral'), CEDICT_URL, None),
        ('cedict.bases_not_in_table', 'CC-CEDICT', 'syllables the dictionary uses that the table lacks', v('cedict.bases_not_in_table'), CEDICT_URL, None),
        ('cedict.bases_missing_from_cedict', 'CC-CEDICT', 'table syllables the dictionary never uses', v('cedict.bases_missing_from_cedict'), CEDICT_URL, None),
        ('cedict.weng_entries', 'CC-CEDICT', 'entries using the syllable weng', v('cedict.weng_entries'), CEDICT_URL, None),

        ('tp.purpleculture', 'Purple Culture', 'publishes a pinyin chart that plays audio', 'yes', PURPLE_URL, PURPLE_QUOTE),
        ('tp.yoyochinese', 'YoYo Chinese', 'publishes an interactive pinyin chart with audio', 'yes', YOYO_URL, YOYO_QUOTE),
        ('tp.yoyochinese_409', 'YoYo Chinese', 'its own chart page names 409 sounds', 409, YOYO_URL, YOYO_409_QUOTE),
    ]
    return [{'id': rid, 'option': option, 'property': prop, 'value': value,
             'url': url, 'quote': quote, 'status': 'measured', 'reason': '',
             'verdict': 'supported'} for rid, option, prop, value, url, quote in r]


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

def build():
    cache = {}
    values = analyse(cache)
    result_rows = rows(values)

    dataset = {
        'slug': 'how-many-mandarin-syllables',
        'product': 'Tingyin',
        'method': 'public-corpus',
        'checkedAt': '2026-10-26',
        'question': 'How many syllables does Mandarin have, and how many distinct toned syllables does the dictionary actually use?',
        'tools': {
            'python': sys.version.split()[0],
            'git': subprocess.run(['git', '--version'], capture_output=True).stdout.decode().split()[2],
        },
        'inputs': [
            {'name': 'CC-CEDICT', 'url': CEDICT_URL,
             'sha256_gz': cache['cedict_sha256_gz'],
             'sha256_txt': cache['cedict_sha256_txt'],
             'entries': cache['cedict_header_entries'],
             'edition_date': cache['cedict_header_date'],
             'license': 'CC BY-SA 4.0'},
            {'name': 'Tingyin pinyin table', 'url': TABLE_SRC},
            {'name': 'Tingyin audio manifest', 'url': MANIFEST_SRC},
            {'name': 'Tingyin level-1 corpus', 'url': API_LEVEL1},
            {'name': 'Tingyin pinyin chart (served HTML)', 'url': CHART_URL},
            {'name': 'Purple Culture pinyin chart', 'url': PURPLE_URL},
            {'name': 'YoYo Chinese pinyin chart', 'url': YOYO_URL},
        ],
        'results': result_rows,
        'notes': [
            {'note': 'Syllables the dictionary uses that the table lacks (13): ' + ', '.join(cache['cedict_extra_bases']),
             'detail': 'weng is the only ordinary one (138 entries, e.g. 翁 weng1, 主人翁 zhu3 ren2 weng1). The other twelve are colloquial, dialectal, Taiwanese, onomatopoeic, interjections (m, hm, hng) or the xx placeholder, and the table excludes standalone nasals by its own header comment. Adding weng alone would make the table 410 cells.'},
            {'note': 'The table file header comment says 412 syllables; the table holds 409 and the post uses 409.',
             'detail': 'Counted from SYLLABLE_TABLE: 409 cells, 409 distinct spellings.'},
            {'note': 'CC-CEDICT is a living file and is re-published often.',
             'detail': 'The measured edition carries entries=' + str(cache['cedict_header_entries']) + ' and date=' + str(cache['cedict_header_date']) + '. check.py prints a warning when the sha256 changes, reports the entry count of a newer edition without failing on it, and fails when any derived count moves.'},
            {'note': 'Yabla was not checked.',
             'detail': 'https://chinese.yabla.com/chinese-pinyin-chart.php answers HTTP 403 behind a Cloudflare "Just a moment..." challenge, with curl and with urllib, on 2026-10-26. No page was read, so the post says nothing about Yabla.'},
            {'note': 'Removed from the post: "have done for years".',
             'detail': 'No page from Purple Culture or YoYo Chinese dates its chart and no dated independent source was found on 2026-10-26, so the age of either chart is not claimed.'},
            {'note': 'The chart without JavaScript was checked structurally, not in a browser.',
             'detail': 'The served HTML carries all 409 cells and their tone forms (chart.summary_cells), which is why the post says the page arrives complete rather than that it works with JavaScript disabled.'},
        ],
    }

    with open(DATASET_JSON, 'w', encoding='utf-8') as f:
        json.dump(dataset, f, ensure_ascii=False, indent=2)
        f.write('\n')

    with open(DATASET_CSV, 'w', encoding='utf-8', newline='') as f:
        w = csv.writer(f)
        w.writerow(['id', 'option', 'property', 'value', 'url', 'quote', 'verdict', 'status', 'reason'])
        for row in result_rows:
            w.writerow([row['id'], row['option'], row['property'], row['value'], row['url'] or '',
                        row['quote'] or '', row['verdict'], row['status'], row['reason']])

    print(f'wrote {DATASET_JSON}')
    print(f'wrote {DATASET_CSV}')


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

def verify():
    with open(DATASET_JSON, encoding='utf-8') as f:
        dataset = json.load(f)
    recorded = {r['id']: r for r in dataset['results']}

    cache = {}
    try:
        values = analyse(cache)
    except Exception as exc:
        print(f'FAIL  could not re-run the measurement: {exc!r}')
        return 1

    failures = 0
    pages = {}
    notes = []

    # CC-CEDICT is re-exported daily, so a recheck almost always reads a newer
    # edition than the one measured. The post dates its entry count to the
    # 26 October 2026 edition, so on a newer edition that count is reported, not
    # failed; every other value derived from the file still has to match.
    recorded_gz = next((i.get('sha256_gz') for i in dataset['inputs'] if i['name'] == 'CC-CEDICT'), None)
    newer_cedict = bool(recorded_gz) and cache.get('cedict_sha256_gz') != recorded_gz
    release_only = {'cedict.entries'}

    for rid, expected in recorded.items():
        if rid.startswith('tp.'):
            url = expected['url']
            try:
                page = pages[url] if url in pages else pages.setdefault(
                    url, http_get(url)[0].decode('utf-8', 'replace'))
            except Exception as exc:
                print(f'FAIL  {rid:34s} {url} unreachable: {exc!r}')
                failures += 1
                continue
            if norm_text(expected['quote']) in html_to_text(page):
                print(f'PASS  {rid:34s} quote still on {url}')
            else:
                print(f'FAIL  {rid:34s} quote no longer on {url}')
                failures += 1
            continue

        actual = values.get(rid, '<not computed>')
        if actual == expected['value']:
            print(f'PASS  {rid:34s} {actual}')
        elif newer_cedict and rid in release_only:
            print(f'NOTE  {rid:34s} recorded {expected["value"]!r}, this edition {actual!r} (reported, not failed)')
            notes.append(rid)
        else:
            print(f'FAIL  {rid:34s} recorded {expected["value"]!r}, now {actual!r}')
            failures += 1

    if recorded_gz and cache.get('cedict_sha256_gz') != recorded_gz:
        print(f'WARN  CC-CEDICT edition changed: sha256 {cache["cedict_sha256_gz"][:16]}... '
              f'(recorded {recorded_gz[:16]}...), counts compared above')

    total = len(recorded)
    print(f'\n{total - failures} of {total} rows hold; {failures} failed')
    return 1 if failures else 0


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument('--build', action='store_true', help='rebuild dataset.json and dataset.csv')
    ap.add_argument('--recheck', action='store_true',
                    help='re-read every source; there is no lab step to skip')
    args = ap.parse_args()

    if args.build:
        build()
        return 0
    return verify()


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