#!/usr/bin/env python3
"""Re-runs the check behind 'Do You Need Tones to Type Chinese Pinyin?'.

1. CC-CEDICT (MDBG export, CC BY-SA 4.0): single-character headwords grouped by
   toneless pinyin syllable, distinct characters counted before and after the
   tone is known.
2. The input-method and dictionary pages the post cites: every quoted sentence
   must still be on its page, and the count of "tone" on Apple's and
   Microsoft's input-method pages must not change.
3. Tingyin's own facts: the public plans endpoint, and the clip manifest and
   source files when the script runs inside the Tingyin repository.

    python3 check.py                  # corpus from --corpus or inputs/, else downloaded
    python3 check.py --recheck        # pages re-read, corpus downloaded fresh
    python3 check.py --emit           # rewrites dataset.json and dataset.csv
    python3 check.py --corpus FILE    # a local cedict_1_0_ts_utf-8_mdbg.txt.gz

Values must match exactly when the corpus file is the 2026-10-25 release
(sha256 below); a newer release may drift by 1 % or one unit, rows matched by
syllable. Exit 0 when everything holds,
1 otherwise. Standard library only.
"""

import argparse
import csv
import gzip
import hashlib
import html
import json
import os
import re
import statistics
import subprocess
import sys
import time
import unicodedata
import urllib.error
import urllib.request
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET_JSON = os.path.join(HERE, 'dataset.json')
DATASET_CSV = os.path.join(HERE, 'dataset.csv')
PINNED = os.path.join(HERE, 'inputs', 'cedict-2026-10-25.txt.gz')

CORPUS_URL = 'https://www.mdbg.net/chinese/export/cedict/cedict_1_0_ts_utf-8_mdbg.txt.gz'
CORPUS_SHA256 = 'f34b5bf7bff705199ea7aef61f140a1fb779a1acf6a7da5c6740a26041c3704b'
PLANS_URL = 'https://api.tingyin.app/subscriptions/plans'
MANIFEST_PATH = 'fixtures/audio-manifest.json'
ENTITLEMENT_PATH = 'apps/api/src/corpus/entitlement.ts'
HOME_PATH = 'apps/web/src/app/(public)/page.tsx'
DRIFT = 0.01
TOP = 20

UA = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 '
      '(KHTML, like Gecko) Version/17.0 Safari/605.1.15')

URLS = {
    'apple': 'https://support.apple.com/guide/chinese-input-method/pinyin-simplified-cimpys11836/mac',
    'microsoft': 'https://support.microsoft.com/en-us/topic/9b962a3b-2fa4-4f37-811c-b1886320dd72',
    'pleco': 'https://www.pleco.com/manual/ios/dict/',
    'cedict_format': 'https://cc-cedict.org/wiki/format:syntax',
    'cedict_home': 'https://cc-cedict.org/wiki/',
}

# Copied from the pages on 2026-10-26; compared after folding quote marks and whitespace.
QUOTES = [
    ('Apple Pinyin - Simplified (macOS)', 'how a character is entered',
     'bare pinyin, then a pick from the candidate window',
     'For example, to enter 苹, type “ping”, then select 苹 in the window.', 'apple'),
    ('Apple Pinyin - Simplified (macOS)', 'v typed in place of ü', 'yes',
     '“v” is used to replace “ü” (so to enter 绿, you would type “lv”)', 'apple'),
    ('Apple Pinyin - Simplified (macOS)', 'several syllables converted at once', 'yes',
     'if you type “pingguogs” with “gongsi” abbreviated to “gs”, the result is still “苹果公司”',
     'apple'),
    ('Microsoft Pinyin (Windows)', 'what the candidate window matches',
     'readings (Pinyin) matching the typed letters',
     'The conversion candidate window offers candidates whose readings (Pinyin) match what is typed.',
     'microsoft'),
    ('Microsoft Pinyin (Windows)', 'how a candidate is chosen', 'number key',
     'Select the corresponding candidate.', 'microsoft'),
    ('Pleco', 'tone numbers accepted', 'yes', 'you’d enter “ni3hao3”', 'pleco'),
    ('Pleco', 'letters without tones accepted', 'yes',
     'You can also enter Pinyin without tones or any spaces between them, like “nihao”', 'pleco'),
    ('Pleco', 'v typed in place of ü', 'yes',
     'To enter an umlaut (ü, as in nü or lü), enter a ‘v’', 'pleco'),
    ('Pleco', 'result order with a tone number', 'frequency-sorted',
     'Searching for “shi4” will get you a nice frequency-sorted list of characters with that exact pronunciation',
     'pleco'),
    ('CC-CEDICT format', 'how a syllable is written in an entry', 'with a tone number',
     'The basic format of a CC-CEDICT entry is: Traditional Simplified '
     '[pin1 yin1] /gloss; gloss; .../gloss; gloss; .../', 'cedict_format'),
    ('CC-CEDICT', 'licence', 'CC BY-SA 4.0',
     'CC-CEDICT is licensed under a Creative Commons Attribution-Share Alike 4.0 License',
     'cedict_home'),
]
TONE_COUNT_PAGES = (('apple', 'Apple Pinyin - Simplified (macOS)'),
                    ('microsoft', 'Microsoft Pinyin (Windows)'))

LINE_RE = re.compile(r'^(\S+)\s+(\S+)\s+\[([^\]]+)\]')
DIGIT_RE = re.compile(r'([0-9])$')


def fetch_bytes(url, attempts=3):
    # Apple's CDN answered 404 to about one request in three on 2026-10-26.
    last = (0, b'')
    for i in range(attempts):
        req = urllib.request.Request(url, headers={
            'User-Agent': UA,
            'Accept': 'text/html,application/json;q=0.9,*/*;q=0.7',
            # Plain en-US, no fallback list. From an EU egress (measured 2026-11-23,
            # NL) 'en-US,en;q=0.9' is sent to /en-euro/, then to the ID-only path,
            # which 404s to urllib every time; plain 'en-US' gets the canonical page.
            'Accept-Language': 'en-US',
        })
        try:
            with urllib.request.urlopen(req, timeout=45) as resp:
                return resp.status, resp.read()
        except urllib.error.HTTPError as exc:
            last = (exc.code, exc.read())
        except Exception as exc:  # noqa: BLE001
            last = (0, str(exc).encode())
        if i + 1 < attempts:
            time.sleep(2)
    return last


def fold(text):
    # Apple writes ü as u plus a combining diaeresis.
    text = unicodedata.normalize('NFC', text)
    for src, dst in (('’', "'"), ('‘', "'"), ('“', '"'), ('”', '"'),
                     ('\u2013', '-'), ('\u2014', '-'), ('\u00a0', ' '), ('\u200b', '')):
        text = text.replace(src, dst)
    return re.sub(r'\s+', ' ', text).strip()


def page_text(raw):
    raw = re.sub(r'(?is)<(script|style|noscript).*?</\1>', ' ', raw)
    raw = re.sub(r'(?s)<[^>]+>', ' ', raw)
    return fold(html.unescape(raw))


def fmt(x):
    if float(x).is_integer():
        return str(int(x))
    return ('%.2f' % x).rstrip('0').rstrip('.')


def toneless(syllable):
    return re.sub(r'[0-9]', '', syllable).lower()


def tone_of(syllable):
    m = DIGIT_RE.search(syllable)
    return m.group(1) if m else '0'


# ---------------------------------------------------------------- corpus

def load_corpus(path, download):
    """(lines, exact, label, problem)."""
    if not download and path and os.path.exists(path):
        with open(path, 'rb') as fh:
            data = fh.read()
        label = path
    else:
        status, data = fetch_bytes(CORPUS_URL)
        if status != 200 or not data:
            return None, False, CORPUS_URL, 'corpus fetch returned %s' % status
        label = CORPUS_URL
    exact = hashlib.sha256(data).hexdigest() == CORPUS_SHA256
    try:
        lines = gzip.decompress(data).decode('utf-8').splitlines()
    except Exception as exc:  # noqa: BLE001
        return None, False, label, 'corpus did not decompress: %s' % exc
    return lines, exact, label, None


def syllable_row(syl, chars, by_tone, rank):
    sizes = [by_tone[t] for t in sorted(by_tone)]
    after = statistics.median(sizes)
    return {
        'syllable': syl,
        'rank': rank,
        'characters_before_tone': chars,
        'tone_1': by_tone.get('1', 0),
        'tone_2': by_tone.get('2', 0),
        'tone_3': by_tone.get('3', 0),
        'tone_4': by_tone.get('4', 0),
        'neutral': by_tone.get('5', 0),
        'median_tone_group': after,
        'cut_percent': round(100.0 * (1 - after / chars), 1),
    }


def measure(lines):
    entries = 0
    tone_digit_entries = 0
    chars_by_syl = defaultdict(set)
    chars_by_toned = defaultdict(set)
    for line in lines:
        if line.startswith('#') or not line.strip():
            continue
        m = LINE_RE.match(line)
        if not m:
            continue
        entries += 1
        _trad, simp, pinyin = m.groups()
        syls = pinyin.split()
        if syls and all(DIGIT_RE.search(s) for s in syls):
            tone_digit_entries += 1
        if len(simp) == 1:
            chars_by_syl[toneless(syls[0])].add(simp)
            chars_by_toned[syls[0].lower()].add(simp)

    by_tone = defaultdict(dict)
    for toned, chars in chars_by_toned.items():
        by_tone[toneless(toned)][tone_of(toned)] = len(chars)

    ranked = sorted(chars_by_syl, key=lambda k: (-len(chars_by_syl[k]), k))
    rows = {syl: syllable_row(syl, len(chars_by_syl[syl]), by_tone[syl], i + 1)
            for i, syl in enumerate(ranked)}
    before = statistics.median(len(v) for v in chars_by_syl.values())
    after = statistics.median(r['median_tone_group'] for r in rows.values())
    summary = {
        'syllable': 'all %d syllables, median' % len(ranked),
        'rank': '',
        'characters_before_tone': before,
        'tone_1': '', 'tone_2': '', 'tone_3': '', 'tone_4': '', 'neutral': '',
        'median_tone_group': after,
        'cut_percent': round(100.0 * (1 - after / before), 1),
    }
    table = [rows[s] for s in ranked[:TOP]]
    if 'ma' not in ranked[:TOP]:
        table.append(rows['ma'])
    table.append(summary)
    aggregates = {
        'entries': entries,
        'entries whose pinyin carries a tone number on every syllable': tone_digit_entries,
        'distinct toneless syllables among single-character headwords': len(ranked),
        'characters per toneless syllable, median': before,
        'characters per toneless syllable, mean': round(statistics.mean(
            len(v) for v in chars_by_syl.values()), 2),
        "median of each syllable's median tone group": after,
        'cut from knowing the tone, 1 minus the ratio of the two medians, %':
            summary['cut_percent'],
    }
    return table, aggregates


CSV_FIELDS = ['syllable', 'rank', 'characters_before_tone', 'tone_1', 'tone_2', 'tone_3',
              'tone_4', 'neutral', 'median_tone_group', 'cut_percent']


def csv_rows(table):
    return [[r[f] if r[f] == '' else fmt(r[f]) if f != 'syllable' else r[f]
             for f in CSV_FIELDS] for r in table]


# ---------------------------------------------------------------- pages and product

def read_pages():
    pages, problems = {}, []
    for key, url in URLS.items():
        status, raw = fetch_bytes(url)
        if status != 200:
            problems.append('page %s returned %s' % (url, status))
        pages[key] = page_text(raw.decode('utf-8', 'replace')) if status == 200 else ''
    return pages, problems


def tone_count(text):
    return len(re.findall(r'\btone', text, re.I))


def find_repo():
    root = os.environ.get('TINGYIN_REPO')
    if not root:
        out = subprocess.run(['git', '-C', HERE, 'rev-parse', '--show-toplevel'],
                             capture_output=True, text=True)
        root = out.stdout.strip() if out.returncode == 0 else ''
    if root and os.path.exists(os.path.join(root, MANIFEST_PATH)):
        return root
    return None


def read_repo_file(repo, path):
    with open(os.path.join(repo, path), encoding='utf-8') as fh:
        return fh.read()


def product_results(repo, plans_text):
    results = [dict(option='Tingyin', property='free tier, plans endpoint',
                    value='level 1 free, level 2 free with an account',
                    quote='Level 1 free, level 2 free with an account.', url=PLANS_URL,
                    source='api', holds=fold('Level 1 free, level 2 free with an account.')
                    in fold(plans_text))]
    if not repo:
        return results
    manifest = json.loads(read_repo_file(repo, MANIFEST_PATH))
    levels = '|'.join(str(sum(1 for c in manifest if c.get('level') == lv)) for lv in (1, 2, 3, 4))
    licences = '|'.join(str(sum(1 for c in manifest if c.get('license') == lic))
                        for lic in ('CC BY-SA 4.0', 'CC0'))
    incomplete = sum(1 for c in manifest
                     if not (c.get('source') and c.get('speaker') and c.get('license')))
    for prop, value in (('clips', str(len(manifest))),
                        ('clips by level (1|2|3|4)', levels),
                        ('clips by licence (CC BY-SA 4.0|CC0)', licences),
                        ('clips missing source, speaker or licence', str(incomplete))):
        results.append(dict(option='Tingyin', property=prop, value=value, quote=None,
                            url=MANIFEST_PATH, source='repo-count'))
    for prop, value, quote, path in (
            ('level served to a caller with no session', '1',
             'A caller with no session gets the one level that needs no account at all',
             ENTITLEMENT_PATH),
            ('what the product asks', 'hear a syllable, pick the tone',
             'Tingyin plays a Mandarin syllable. You pick the tone you heard.', HOME_PATH)):
        results.append(dict(option='Tingyin', property=prop, value=value, quote=quote,
                            url=path, source='repo', holds=fold(quote) in fold(
                                read_repo_file(repo, path))))
    return results


def build(corpus_path, download):
    problems = []
    lines, exact, label, err = load_corpus(corpus_path, download)
    if err:
        return None, [err]
    table, aggregates = measure(lines)
    pages, page_problems = read_pages()
    problems += page_problems
    status, plans = fetch_bytes(PLANS_URL)
    if status != 200:
        problems.append('plans endpoint returned %s' % status)
    plans_text = plans.decode('utf-8', 'replace') if status == 200 else ''

    results = [dict(option='CC-CEDICT 2026-10-25', property=k, value=fmt(v), quote=None,
                    url=CORPUS_URL, source='corpus') for k, v in aggregates.items()]
    for r in table:
        for f in CSV_FIELDS[2:]:
            if r[f] != '':
                results.append(dict(option=r['syllable'], property=f, value=fmt(r[f]),
                                    quote=None, url=CORPUS_URL, source='corpus'))
    for option, prop, value, quote, key in QUOTES:
        results.append(dict(option=option, property=prop, value=value, quote=quote,
                            url=URLS[key], source='page', holds=fold(quote) in pages[key]))
    for key, option in TONE_COUNT_PAGES:
        results.append(dict(option=option, property='occurrences of "tone" on the page',
                            value=str(tone_count(pages[key])), quote=None, url=URLS[key],
                            source='page-count'))
    repo = find_repo()
    results += product_results(repo, plans_text)
    return dict(table=table, results=results, exact=exact, corpus=label, repo=repo), problems


# ---------------------------------------------------------------- emit and verify

def emit(state):
    with open(DATASET_JSON, encoding='utf-8') as fh:
        ds = json.load(fh)
    ds['results'] = [{k: v for k, v in r.items() if k != 'holds'} for r in state['results']]
    with open(DATASET_JSON, 'w', encoding='utf-8') as fh:
        json.dump(ds, fh, ensure_ascii=False, indent=1)
        fh.write('\n')
    with open(DATASET_CSV, 'w', encoding='utf-8', newline='') as fh:
        w = csv.writer(fh)
        w.writerow(CSV_FIELDS)
        w.writerows(csv_rows(state['table']))


def same(a, b, exact):
    if a == b:
        return True
    if exact:
        return False
    # A newer release moves a small count by one character, which is more than
    # 1 % of 25: allow one unit as well (yu, tone 3: 25 -> 24 on 2026-11-02).
    try:
        return abs(float(a) - float(b)) <= max(DRIFT * abs(float(b)), 1)
    except ValueError:
        return False


def verify(state, problems):
    with open(DATASET_JSON, encoding='utf-8') as fh:
        recorded = json.load(fh)['results']
    with open(DATASET_CSV, encoding='utf-8') as fh:
        csv_recorded = list(csv.reader(fh))[1:]
    exact = state['exact']
    now = {(r['option'], r['property']): r for r in state['results']}
    checked = 0
    for r in recorded:
        key = (r['option'], r['property'])
        if r['source'] in ('repo', 'repo-count') and not state['repo']:
            print('  not re-checked: %s / %s (no Tingyin repository here)' % key)
            continue
        cur = now.get(key)
        checked += 1
        if cur is None:
            problems.append('%s / %s: not measured any more' % key)
        elif cur.get('holds') is False:
            problems.append('%s / %s: quote no longer found on %s' % (key + (r['url'],)))
        elif not same(r['value'], cur['value'], exact and r['source'] != 'page-count'):
            problems.append('%s / %s: dataset says %s, now %s'
                            % (key + (r['value'], cur['value'])))
    # Rows are matched by syllable, not by position: on a newer release two
    # syllables that tie on characters_before_tone can swap ranks.
    new_rows = csv_rows(state['table'])
    by_syl = {r[0]: r for r in new_rows}
    for i, old in enumerate(csv_recorded):
        checked += 1
        new = (new_rows[i] if i < len(new_rows) else None) if exact else by_syl.get(old[0])
        if new is None or old[0] != new[0] or not all(same(a, b, exact) for a, b in zip(old[2:], new[2:])):
            problems.append('dataset.csv row %s: now %s' % (old, new))
    print('corpus: %s (%s)' % (state['corpus'], 'the 2026-10-25 release, exact'
                               if exact else 'another release, 1 % or one unit of drift allowed'))
    if problems:
        print('%d of %d checks failed' % (len(problems), checked))
        for p in problems:
            print('  FAIL', p)
        return 1
    print('all %d checks hold' % checked)
    return 0


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--recheck', action='store_true',
                        help='re-read the pages and download the current corpus')
    parser.add_argument('--emit', action='store_true')
    parser.add_argument('--corpus', default=PINNED)
    args = parser.parse_args()
    state, problems = build(args.corpus, args.recheck)
    if state is None:
        for p in problems:
            print('  FAIL', p)
        return 1
    if args.emit:
        emit(state)
        print('wrote dataset.json and dataset.csv')
        return 0
    return verify(state, problems)


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