#!/usr/bin/env python3
"""Re-runs the evidence check behind 'how long to learn Chinese'.

The post's own numbers are aggregates of Tingyin's production analytics and
database, counted on 2026-10-26 with query.hogql and query.js. This script
cannot reach production, so for those rows it re-derives every published value
from the raw aggregates stored in dataset.json and enforces the counts-only rule
(no published cell from fewer than 10 people). It also re-reads every page a
third-party statement rests on, the Tingyin plans endpoint and the repository's
audio manifest.

    python3 check.py            # everything
    python3 check.py --recheck  # the same; nothing here takes longer than a minute

Exit 0 when everything holds, 1 otherwise. Standard library only.
"""

import csv
import html
import json
import os
import re
import subprocess
import sys
import unicodedata
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET_CSV = os.path.join(HERE, 'dataset.csv')
DATASET_JSON = os.path.join(HERE, 'dataset.json')
PLANS_URL = 'https://api.tingyin.app/subscriptions/plans'
MIN_GROUP = 10

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')


def fetch(url):
    """Returns (status, body). Non-200 is a result, not an exception."""
    req = urllib.request.Request(url, headers={
        'User-Agent': UA,
        'Accept': 'text/html,application/json;q=0.9,text/plain;q=0.8,*/*;q=0.7',
        'Accept-Language': 'en-US,en;q=0.9',
    })
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return resp.status, resp.read()
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read()
    except Exception as exc:  # noqa: BLE001 - reported, never raised
        return 0, str(exc).encode()


def fold(text):
    for src, dst in (('\u2019', "'"), ('\u2018', "'"), ('\u201c', '"'),
                     ('\u201d', '"'), ('\u2013', '-'), ('\u2014', '-'),
                     ('\u00a0', ' '), ('\u200b', '')):
        text = text.replace(src, dst)
    return re.sub(r'\s+', ' ', text).strip()


def visible_text(raw, is_html=True):
    text = raw.decode('utf-8', 'replace')
    if is_html:
        text = re.sub(r'(?is)<(script|style|noscript).*?</\1>', ' ', text)
        text = re.sub(r'(?s)<[^>]+>', ' ', text)
    return fold(html.unescape(text))


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

def lookup(data, path):
    node = data
    for part in path.split('.'):
        node = node[int(part)] if isinstance(node, list) else node[part]
    return node


def same(got, want):
    try:
        return float(got) == float(want)
    except (TypeError, ValueError):
        return str(got) == str(want)


def check_data(kind, row, data):
    """Returns None when the row holds, else the reason."""
    rule, arg = kind.split(':', 1)
    if rule == 'data':
        got = lookup(data, arg)
        return None if same(got, row['value']) else 'stored %s, csv says %s' % (got, row['value'])
    if rule == 'pct':
        num, den = (lookup(data, p) for p in arg.split('/'))
        got = round(100.0 * num / den, 1)
        return None if same(got, row['value']) else '%s/%s is %s, csv says %s' % (num, den, got, row['value'])
    if rule == 'round1':
        got = round(lookup(data, arg), 1)
        return None if same(got, row['value']) else 'stored %s, csv says %s' % (got, row['value'])
    if rule == 'suppressed':
        got = lookup(data, arg)
        return None if got is None else 'expected a suppressed count, found %s' % got
    return 'unknown rule %r' % rule


def check_invariants(data):
    """The counts-only rule and the internal sums the queries must satisfy."""
    problems = []
    ph, mg = data['posthog'], data['mongo']
    counts = [('posthog.totals.persons', ph['totals']['persons']),
              ('posthog.totals.level1_persons', ph['totals']['level1_persons'])]
    for key in ('persons_under_100', 'persons_100_plus', 'persons_more_than_one_day'):
        counts.append(('posthog.perperson.' + key, ph['perperson'][key]))
    for key, value in mg.items():
        if key.startswith(('accounts', 'user_progress')) and isinstance(value, int):
            counts.append(('mongo.' + key, value))
    previous = None
    for i, row in enumerate(ph['curve']):
        base = 'posthog.curve.%d.' % i
        counts.append((base + 'persons', row['persons']))
        if row['persons_better'] is not None:
            counts.append((base + 'persons_better', row['persons_better']))
            counts.append((base + 'persons_not_better', row['persons'] - row['persons_better']))
        for side in ('first20', 'lastK'):
            if row[side + '_total'] != 20 * row['persons']:
                problems.append('%s%s_total is not 20 per learner' % (base, side))
            if not 0 <= row[side + '_correct'] <= row[side + '_total']:
                problems.append('%s%s_correct is outside 0..total' % (base, side))
        if previous is not None and (row['K'] <= previous['K'] or row['persons'] > previous['persons']):
            problems.append('%s learners grow with a higher threshold' % base)
        previous = row
    for key, value in counts:
        if value is not None and value < MIN_GROUP:
            problems.append('%s = %s is a group under %d' % (key, value, MIN_GROUP))
    totals = ph['totals']
    if not totals['level1_answers'] <= totals['answers']:
        problems.append('level 1 answers exceed all answers')
    if not totals['level1_persons'] <= totals['persons']:
        problems.append('level 1 persons exceed all persons')
    if ph['perperson']['persons_under_100'] + ph['perperson']['persons_100_plus'] != totals['persons']:
        problems.append('persons under and over 100 answers do not add up to all persons')
    if mg['accounts_other'] + mg['accounts_test_or_internal'] != mg['accounts_total']:
        problems.append('accounts do not add up')
    return problems


# -------------------------------------------------------------- manifest ----

def measure_manifest():
    try:
        root = subprocess.run(['git', '-C', HERE, 'rev-parse', '--show-toplevel'],
                              capture_output=True, text=True, check=True).stdout.strip()
        with open(os.path.join(root, 'fixtures', 'audio-manifest.json'), encoding='utf-8') as handle:
            entries = json.load(handle)
    except Exception as exc:  # noqa: BLE001
        return None, 'could not read fixtures/audio-manifest.json: %s' % exc

    def base(pinyin):
        decomposed = unicodedata.normalize('NFD', pinyin)
        return ''.join(c for c in decomposed if not unicodedata.combining(c))

    level1 = [e for e in entries if e['level'] == 1]
    return {
        'entries': len(entries),
        'three_then_three': sum(1 for e in entries if e['tones'][:2] == [3, 3]),
        'level1': len(level1),
        'level1_syllables': len({base(e['pinyin']) for e in level1}),
        'min_syllables': min(e['syllableCount'] for e in entries),
        'max_syllables': max(e['syllableCount'] for e in entries),
    }, 'fixtures/audio-manifest.json'


# ---------------------------------------------------------------- plans ----

def measure_plans():
    status, body = fetch(PLANS_URL)
    if status != 200:
        return None, 'plans endpoint answered HTTP %s' % status
    payload = json.loads(body.decode('utf-8'))
    tiers = {plan['tier']: plan for plan in payload['plans']}
    values = {'free.maxCorpusLevel': tiers['free']['limits']['maxCorpusLevel'],
              'premium.maxCorpusLevel': tiers['premium']['limits']['maxCorpusLevel']}
    for tier in ('free', 'premium'):
        for flag, on in tiers[tier]['features'].items():
            values['%s.%s' % (tier, flag)] = on
    for option in tiers['premium']['pricing']['options']:
        for channel in ('web', 'store'):
            if channel in option:
                values['premium.%s.%s' % (option['id'], channel)] = option[channel]
    return values, ''


# --------------------------------------------------------------- report ----

def main():
    with open(DATASET_CSV, newline='', encoding='utf-8') as handle:
        rows = list(csv.DictReader(handle))
    with open(DATASET_JSON, encoding='utf-8') as handle:
        dataset = json.load(handle)

    failures, passes = [], []
    if [{k: r[k] for k in rows[0]} for r in dataset['results']] != rows:
        failures.append('dataset.json results and dataset.csv differ')
    failures.extend('invariant: %s' % p for p in check_invariants(dataset['data']))

    manifest_values, manifest_detail = None, ''
    plans_values, plans_detail = None, ''
    page_cache = {}

    for row in rows:
        label = '%s / %s' % (row['item'], row['property'])
        kind = row['check']

        if kind.split(':', 1)[0] in ('data', 'pct', 'round1', 'suppressed'):
            reason = check_data(kind, row, dataset['data'])
            (failures.append('%s - %s' % (label, reason)) if reason
             else passes.append('%s = %s' % (label, row['value'])))
            continue

        if kind == 'quote':
            url = row['url']
            if url not in page_cache:
                status, body = fetch(url)
                page_cache[url] = (status, visible_text(body, is_html=not url.startswith(
                    ('https://api.', 'https://itunes.apple.com', 'https://eutils.ncbi'))))
            status, text = page_cache[url]
            if status != 200:
                failures.append('%s - page answered HTTP %s (%s)' % (label, status, url))
            elif fold(row['quote']) in text:
                passes.append('%s = %s' % (label, row['value']))
            else:
                failures.append('%s - quote no longer on %s: %r' % (label, url, row['quote']))
            continue

        if kind.startswith('manifest:'):
            if manifest_values is None:
                manifest_values, manifest_detail = measure_manifest()
            if manifest_values is None:
                failures.append('%s - %s' % (label, manifest_detail))
                continue
            got = manifest_values[kind.split(':', 1)[1]]
            (passes.append('%s = %s' % (label, got)) if got == int(row['value'])
             else failures.append('%s - manifest now has %s, dataset says %s' % (label, got, row['value'])))
            continue

        if kind.startswith('plans:'):
            if plans_values is None:
                plans_values, plans_detail = measure_plans()
            if plans_values is None:
                failures.append('%s - %s' % (label, plans_detail))
                continue
            got = plans_values.get(kind.split(':', 1)[1])
            want = row['value'].strip()
            if got is None:
                failures.append('%s - missing from the plans endpoint' % label)
            elif isinstance(got, bool):
                (passes.append('%s = %s' % (label, want)) if str(got).lower() == want.lower()
                 else failures.append('%s - endpoint now says %s, dataset says %s' % (label, got, want)))
            elif ('%.2f' % got) == ('%.2f' % float(want)):
                passes.append('%s = %s' % (label, want))
            else:
                failures.append('%s - endpoint now says %s, dataset says %s' % (label, got, want))
            continue

        failures.append('%s - unknown check %r' % (label, kind))

    for line in passes:
        print('PASS %s' % line)
    for line in failures:
        print('FAIL %s' % line)
    print('\n%d passed, %d failed' % (len(passes), len(failures)))
    return 0 if not failures else 1


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