#!/usr/bin/env python3
"""Re-runs the check behind /blog/mandarin-tone-sandhi.

What it measures, per level of Tingyin's corpus: how many clips are said with a
tone their written (dictionary) form does not show, and which rule causes it.
It then reads CC-CEDICT, an independent open dictionary, to see whether the
written tones are the dictionary's and whether the dictionary ever spells the
spoken form. Prices and level limits come from Tingyin's public plans endpoint.

Sources:
  - the corpus Tingyin ships, apps/api/src/corpus/corpus.generated.ts (found by
    walking up from this file, or passed with --corpus); the public endpoint
    https://api.tingyin.app/corpus serves its level-1 part to anyone,
  - https://api.tingyin.app/corpus/coverage and /subscriptions/plans,
  - the CC-CEDICT export at mdbg.net (about 4 MB, downloaded each run).

The production counts in dataset.json cannot be re-read from here: they are
checked for internal consistency only.

Exit 0 when every row holds, 1 when any row fails. --recheck re-reads the
pages and the dictionary only and skips the rows built on the repository file.
--write regenerates the results in dataset.json and dataset.csv.
"""

import argparse
import csv
import gzip
import html
import io
import json
import os
import re
import sys
import urllib.error
import urllib.request
from collections import defaultdict

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, "dataset.json")
CSV_PATH = os.path.join(HERE, "dataset.csv")
API = "https://api.tingyin.app"
COVERAGE = API + "/corpus/coverage"
CORPUS_L1 = API + "/corpus"
PLANS = API + "/subscriptions/plans"
CEDICT = "https://www.mdbg.net/chinese/export/cedict/cedict_1_0_ts_utf-8_mdbg.txt.gz"
TIMEOUT = 60


class Skip(Exception):
    pass


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
        return response.read()


def fetch_json(url):
    return json.loads(fetch(url).decode("utf-8"))


def find_corpus(explicit):
    if explicit:
        return explicit if os.path.isfile(explicit) else None
    directory = HERE
    for _ in range(8):
        path = os.path.join(directory, "apps", "api", "src", "corpus", "corpus.generated.ts")
        if os.path.isfile(path):
            return path
        directory = os.path.dirname(directory)
    return None


def load_corpus(path):
    text = open(path, encoding="utf-8").read()
    return json.loads(text[text.index("= [") + 2 : text.rindex("]") + 1])


def syllable_chars(item):
    """One character per syllable; an erhua 儿 fused into its host syllable is dropped."""
    chars = list(item["hanzi"])
    if len(chars) > item["syllableCount"] and chars[-1] == "儿":
        chars = chars[:-1]
    if len(chars) != item["syllableCount"]:
        raise AssertionError("cannot align %s to %d syllables" % (item["hanzi"], item["syllableCount"]))
    return chars


def kind_of(item):
    """Why the spoken tones differ from the written ones, or None when they do not."""
    kinds = set()
    chars = syllable_chars(item)
    for index, (written, spoken) in enumerate(zip(item["citationTones"], item["tones"])):
        if written == spoken:
            continue
        if chars[index] == "一":
            kinds.add("yi")
        elif chars[index] == "不":
            kinds.add("bu")
        elif written == 3 and spoken == 2 and item["citationTones"][index + 1] == 3:
            kinds.add("t3t3")
        else:
            kinds.add("other")
    if len(kinds) > 1:
        raise AssertionError("%s changes for more than one reason: %s" % (item["hanzi"], sorted(kinds)))
    return kinds.pop() if kinds else None


def syllable_label(items):
    counts = defaultdict(int)
    for item in items:
        counts[item["syllableCount"]] += 1
    if len(counts) == 1:
        return str(next(iter(counts)))
    return " or ".join("%d (%d)" % (n, counts[n]) for n in sorted(counts))


def corpus_rows(items):
    rows = {}
    levels = sorted({item["level"] for item in items})
    for level in levels + ["all"]:
        chosen = [item for item in items if level == "all" or item["level"] == level]
        kinds = [kind_of(item) for item in chosen]
        rows[str(level)] = {
            "clips": len(chosen),
            "syllables": "1 to 4" if level == "all" else syllable_label(chosen),
            "neutral": sum(1 for item in chosen if 5 in item["tones"]),
            "differs": sum(1 for kind in kinds if kind),
            "t3t3": kinds.count("t3t3"),
            "yi": kinds.count("yi"),
            "bu": kinds.count("bu"),
            "other": kinds.count("other"),
            "flagged": sum(1 for item in chosen if item["sandhi"]),
        }
    extra = {
        "contains-yi": sum(1 for item in items if "一" in item["hanzi"]),
        "contains-bu": sum(1 for item in items if "不" in item["hanzi"]),
        "yi-unchanged": ", ".join(
            sorted(item["hanzi"] for item in items if "一" in item["hanzi"] and kind_of(item) != "yi")
        ),
        "spoken-t3t3": sum(
            1
            for item in items
            if any(a == 3 and b == 3 for a, b in zip(item["tones"], item["tones"][1:]))
        ),
        "written-t3t3": sum(
            1
            for item in items
            if any(a == 3 and b == 3 for a, b in zip(item["citationTones"], item["citationTones"][1:]))
        ),
        "words-in-table": "; ".join(
            "%s %s > %s"
            % (item["hanzi"], item["citationPinyin"], item["pinyin"])
            for word in ("水果", "可以", "所以", "手表", "一半", "一些", "一起", "不错", "一路平安", "一口气")
            for item in items
            if item["hanzi"] == word
        ),
    }
    return rows, extra


def public_rows():
    coverage = {entry["level"]: entry for entry in fetch_json(COVERAGE)["data"]}
    level1 = fetch_json(CORPUS_L1)["data"]
    plans = {plan["tier"]: plan for plan in fetch_json(PLANS)["plans"]}
    return {
        "api-coverage-totals": ", ".join(
            "%d: %d" % (level, coverage[level]["total"]) for level in sorted(coverage)
        ),
        "api-coverage-neutral": ", ".join(
            "%d: %d" % (level, coverage[level]["itemsWithTone"].get("5", 0)) for level in sorted(coverage)
        ),
        "api-level1-clips": len(level1),
        "api-level1-differs": sum(1 for item in level1 if item["tones"] != item["citationTones"]),
        "api-free-max-level": plans["free"]["limits"]["maxCorpusLevel"],
        "api-free-description": plans["free"]["description"],
        "api-premium-max-level": plans["premium"]["limits"]["maxCorpusLevel"],
        "api-premium-features": "progressSync=%s, offlineDownloads=%s"
        % (
            str(plans["premium"]["features"]["progressSync"]).lower(),
            str(plans["premium"]["features"]["offlineDownloads"]).lower(),
        ),
    }


def load_cedict():
    raw = gzip.GzipFile(fileobj=io.BytesIO(fetch(CEDICT))).read().decode("utf-8")
    readings = defaultdict(list)
    header = {}
    for line in raw.splitlines():
        if line.startswith("#!"):
            key, _, value = line[2:].strip().partition("=")
            header[key] = value
            continue
        if line.startswith("#"):
            continue
        match = re.match(r"(\S+) (\S+) \[([^\]]+)\]", line)
        if match:
            readings[match.group(2)].append(match.group(3).split())
    return header, readings


def cedict_tones(syllables, erhua):
    if erhua and syllables and syllables[-1].lower() == "r5":
        syllables = syllables[:-1]
    return [int(s[-1]) if s[-1].isdigit() else 5 for s in syllables]


def cedict_rows(items, header, readings):
    agree = neutral = missing = conflict = spoken_listed = 0
    differs = 0
    for item in items:
        if item["syllableCount"] < 2:
            continue
        entries = readings.get(item["hanzi"])
        if not entries:
            missing += 1
            continue
        erhua = len(item["hanzi"]) > item["syllableCount"]
        tones = [cedict_tones(entry, erhua) for entry in entries]
        written = item["citationTones"]
        if written in tones:
            agree += 1
        elif any(
            len(t) == len(written) and all(a == b or 5 in (a, b) for a, b in zip(t, written)) for t in tones
        ):
            neutral += 1
        else:
            conflict += 1
        if item["tones"] != written:
            differs += 1
            spoken_listed += int(item["tones"] in tones)
    return {
        "cedict-licence": header.get("license", ""),
        "cedict-words": agree + neutral + missing + conflict,
        "cedict-agree": agree,
        "cedict-neutral-only": neutral,
        "cedict-conflict": conflict,
        "cedict-missing": missing,
        "cedict-spoken-form-listed": "%d of %d" % (spoken_listed, differs),
    }


def measure(recheck, corpus_argument):
    values, notes = {}, []
    values.update(public_rows())
    header, readings = load_cedict()
    notes.append("CC-CEDICT export dated %s, %s entries" % (header.get("date"), header.get("entries")))
    path = None if recheck else find_corpus(corpus_argument)
    if path:
        items = load_corpus(path)
        rows, extra = corpus_rows(items)
        for level, row in rows.items():
            for key, value in row.items():
                values["corpus-%s-%s" % (level, key)] = value
        values.update(extra)
        values.update(cedict_rows(items, header, readings))
    else:
        level1 = fetch_json(CORPUS_L1)["data"]
        values["cedict-licence"] = header.get("license", "")
        notes.append(
            "repository corpus %s, so the rows built on it are skipped"
            % ("not read under --recheck" if recheck else "not found")
        )
        del level1
    return values, notes


def check_production(dataset):
    """The production counts cannot be re-read here; every cell must be suppressed or sum."""
    output = dataset["productData"]["output"]
    problems = []
    for level, cell in output["levels"].items():
        users = cell.get("users")
        if isinstance(users, int) and 0 < users < 10:
            problems.append("level %s shows %d users, under the floor of 10" % (level, users))
        if isinstance(users, int) and users >= 10:
            tone_sum = sum(cell["t%sasked" % t] for t in "12345")
            if tone_sum < cell["answered"]:
                problems.append("level %s: tone counts %d below answers %d" % (level, tone_sum, cell["answered"]))
    if isinstance(output["docs"], int) and output["docs"] < 10:
        problems.append("document count %d is under the floor of 10" % output["docs"])
    return problems


def sums(values):
    problems = []
    levels = [k[len("corpus-") : -len("-clips")] for k in values if k.startswith("corpus-") and k.endswith("-clips")]
    for level in levels:
        p = "corpus-%s-" % level
        if values[p + "t3t3"] + values[p + "yi"] + values[p + "bu"] + values[p + "other"] != values[p + "differs"]:
            problems.append("level %s: rule counts do not add up to %d" % (level, values[p + "differs"]))
        if values[p + "flagged"] != values[p + "differs"]:
            problems.append("level %s: %d flagged as sandhi, %d differ" % (level, values[p + "flagged"], values[p + "differs"]))
    numeric = [l for l in levels if l != "all"]
    for key in ("clips", "neutral", "differs", "t3t3", "yi", "bu", "other"):
        if numeric and sum(values["corpus-%s-%s" % (l, key)] for l in numeric) != values["corpus-all-%s" % key]:
            problems.append("levels do not add up to the total for %s" % key)
    return problems


CSV_COLUMNS = [
    ("level", None),
    ("clips", "clips"),
    ("syllables_per_clip", "syllables"),
    ("clips_with_neutral_tone", "neutral"),
    ("clips_said_differently_from_written", "differs"),
    ("of_which_third_before_third", "t3t3"),
    ("of_which_yi", "yi"),
    ("of_which_bu", "bu"),
    ("of_which_other", "other"),
]


def write(values, notes):
    dataset = json.load(open(DATASET, encoding="utf-8"))
    dataset["results"] = [{"id": key, "value": value} for key, value in values.items()]
    dataset["runNotes"] = notes
    with open(DATASET, "w", encoding="utf-8") as handle:
        json.dump(dataset, handle, ensure_ascii=False, indent=2)
        handle.write("\n")
    with open(CSV_PATH, "w", encoding="utf-8", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow([name for name, _ in CSV_COLUMNS])
        for level in ("1", "2", "3", "4", "all"):
            writer.writerow(
                [level if key is None else values["corpus-%s-%s" % (level, key)] for _, key in CSV_COLUMNS]
            )


def compare(values, notes, dataset):
    stored = {row["id"]: row["value"] for row in dataset["results"]}
    failures = skipped = 0
    for key, expected in stored.items():
        if key not in values:
            skipped += 1
            print("SKIP  %s" % key)
            continue
        if str(values[key]) != str(expected):
            failures += 1
            print("FAIL  %s = %r, dataset says %r" % (key, values[key], expected))
        else:
            print("ok    %s = %s" % (key, values[key]))
    for problem in sums(values) + check_production(dataset):
        failures += 1
        print("FAIL  %s" % problem)
    if any(k.startswith("corpus-") for k in values):
        csv_rows = list(csv.DictReader(open(CSV_PATH, encoding="utf-8")))
        for row in csv_rows:
            for name, key in CSV_COLUMNS[1:]:
                if str(values["corpus-%s-%s" % (row["level"], key)]) != row[name]:
                    failures += 1
                    print("FAIL  dataset.csv level %s %s = %s" % (row["level"], name, row[name]))
    for note in notes:
        print("note  %s" % note)
    print("\n%d rows, %d failed, %d skipped" % (len(stored), failures, skipped))
    return 1 if failures else 0


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--recheck", action="store_true", help="re-read the pages and the dictionary only")
    parser.add_argument("--corpus", help="path to apps/api/src/corpus/corpus.generated.ts")
    parser.add_argument("--write", action="store_true", help="regenerate the results in dataset.json and dataset.csv")
    arguments = parser.parse_args()
    try:
        values, notes = measure(arguments.recheck, arguments.corpus)
    except (urllib.error.URLError, OSError) as error:
        print("FAIL  could not fetch a source: %s" % error)
        return 1
    if arguments.write:
        write(values, notes)
        print("wrote %d results" % len(values))
        return 0
    return compare(values, notes, json.load(open(DATASET, encoding="utf-8")))


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