#!/usr/bin/env python3
"""Re-runs the evidence behind the post «Which Thai app uses typing instead of multiple choice?».

Four sections:
  1. results  : every named alternative's own page, one row per option and property.
  2. product  : sentences the post makes about Phayan itself, checked against the app's
                 source files of the repository this script sits in.
  3. price    : Phayan's plans endpoint, in USD.
  4. recount  : the post's numbers, re-derived from the curriculum seed in this repository.

Exit 0 when every row holds, 1 otherwise. `--recheck` re-reads the pages and re-runs the
same steps (none of them takes more than a minute, so nothing is skipped).
"""

import argparse
import html
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(HERE, "dataset.json")
REPO = os.path.abspath(os.path.join(HERE, "..", "..", "..", "..", ".."))
REF = "working tree"
# thai-keyboard.ts THAI_KEY: consonants, vowel signs and tone marks.
THAI_KEY = re.compile("[\u0e01-\u0e3a\u0e40-\u0e4e]")
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"


def fetch(url, hops=4):
    """urllib does not follow 308; the Anki manual answers one, so redirects are
    walked here and the final body returned."""
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    try:
        with urllib.request.urlopen(req, timeout=45) as resp:
            raw = resp.read()
            charset = resp.headers.get_content_charset() or "utf-8"
        return raw.decode(charset, "replace")
    except urllib.error.HTTPError as exc:
        location = exc.headers.get("Location") if exc.headers else None
        if exc.code in (301, 302, 303, 307, 308) and location and hops > 0:
            return fetch(urllib.parse.urljoin(url, location), hops - 1)
        raise


def norm(text):
    """Whitespace, quote glyphs and entities normalised the way the comparison needs."""
    text = html.unescape(html.unescape(text))
    for a, b in (
        ("’", "'"),
        ("‘", "'"),
        ("“", '"'),
        ("”", '"'),
        ("\u2013", "-"),
        ("\u2014", "-"),
        (" ", " "),
        ("​", ""),
    ):
        text = text.replace(a, b)
    return re.sub(r"\s+", " ", text).strip()


def page_text(raw):
    """Visible text plus meta/link attribute values: a page's own claim can live in a
    meta description, and a script-only shell leaves the visible text empty."""
    metas = " ".join(re.findall(r'content="([^"]*)"', raw))
    body = re.sub(r"<script.*?</script>", " ", raw, flags=re.S | re.I)
    body = re.sub(r"<style.*?</style>", " ", body, flags=re.S | re.I)
    body = re.sub(r"<[^>]+>", " ", body)
    return norm(body + " " + metas)


def read_repo(path):
    """Reads a file of the Phayan repository this script sits in."""
    try:
        with open(os.path.join(REPO, path), encoding="utf-8") as fh:
            return fh.read()
    except OSError as exc:
        raise RuntimeError("cannot read %s (%s)" % (path, exc))


# --- the curriculum recount -------------------------------------------------
# The rules it applies are quoted from the source in dataset.json under
# "recount_rules"; each rule's marker string is asserted below so a change in the
# app's own definition of "buildable", "review round" or "picture distractor"
# fails the check instead of silently changing a number.

def split_levels(src):
    levels = []
    for block in re.split(r"\n  \{\n    id: 'L", src)[1:]:
        number = int(re.match(r"(\d+)'", block).group(1))
        rounds = []
        for chunk in re.split(r"\n      \{\n        id: '", block)[1:]:
            rid = chunk.split("'", 1)[0]
            m = re.search(r"wordIds: \[(.*?)\]", chunk, re.S)
            rounds.append((number, rid, re.findall(r"'([^']+)'", m.group(1)) if m else []))
        levels.append((number, rounds))
    return levels


def parse_words(src):
    """Spelling -> (introducedLevel, decodableFrom, paiboon, tone)."""
    words = {}
    for block in re.split(r"\n  w\(", src)[1:]:
        first = re.search(
            r"'([^']*)'\s*,\s*'([^']*)'\s*,\s*(\d)\s*,\s*'([^']*)'", block
        )
        m = re.search(r"(\d+),\s*\[([^\]]*)\]", block)
        if not m or not first:
            continue
        word = first.group(1)
        words[word] = {
            "introducedLevel": int(m.group(1)),
            "decodableFrom": re.findall(r"'([^']*)'", m.group(2)),
            "paiboon": first.group(4),
            "tone": int(first.group(3)),
            "word": first.group(1),
        }
    return words


def parse_images(src):
    return {
        m.group(1): {"emoji": m.group(2), "src": m.group(3)}
        for m in re.finditer(
            r"^  ([^ :{]+): \{ emoji: '([^']*)', alt: '[^']*', src: (null|'[^']*') \}",
            src,
            re.M,
        )
    }


def recount():
    levels_src = read_repo("apps/api/src/content/seed/levels.ts")
    words_src = read_repo("apps/api/src/content/seed/words.ts")
    images_src = read_repo("apps/web/src/components/learn/picture-choice/word-images.ts")
    buildable_src = read_repo("apps/web/src/components/learn/word-build/buildable.ts")
    steps_src = read_repo("apps/web/src/components/learn/round-flow/steps.ts")
    router_src = read_repo("apps/web/src/components/learn/round-content/RoundStepContent.tsx")
    keyboard_src = read_repo("apps/web/src/components/learn/typing-practice/thai-keyboard.ts")

    keyboard_block = re.search(r"THAI_KEYBOARD_ROWS[^=]*=\s*\[(.*?)\n\];", keyboard_src, re.S)
    keyboard_keys = len(re.findall(r"'([^'])'", keyboard_block.group(1))) if keyboard_block else 0
    base_keys = set(re.findall(r"'([^'])'", keyboard_block.group(1))) if keyboard_block else set()

    # The card's keyboard = the 26 base keys plus every key the round needs and the
    # base rows cut off (thai-keyboard.ts buildKeyboardRows; the round's letters and
    # words are what TypingPractice feeds it).
    round_keyboards = {}
    for block in re.split(r"\n  \{\n    id: 'L", levels_src)[1:]:
        number = int(re.match(r"(\d+)'", block).group(1))
        for chunk in re.split(r"\n      \{\n        id: '", block)[1:]:
            rid = chunk.split("'", 1)[0]
            m = re.search(r"wordIds: \[(.*?)\]", chunk, re.S)
            nl = re.search(r"newLetters: \[(.*?)\]", chunk, re.S)
            ws = re.findall(r"'([^']+)'", m.group(1)) if m else []
            needed = {
                ch
                for ch in "".join(ws) + "".join(re.findall(r"'([^']+)'", nl.group(1)) if nl else [])
                if THAI_KEY.match(ch)
            }
            round_keyboards[(number, rid)] = (ws, len(base_keys | needed))

    rules_ok = {
        "keyboard_is_kedmanee_cut_down": "KEDMANEE_REST" in keyboard_src,
        "buildable_is_a_written_vowel": "id.includes('-')" in buildable_src,
        "picture_distractor_needs_shared_letter_or_tone": "sharesLetter(candidate.word, target.word) ? 2 : 0" in steps_src,
        "review_round_shape": "word.introducedLevel < round.level.number" in router_src,
    }

    levels = split_levels(levels_src)
    words = parse_words(words_src)
    images = parse_images(images_src)
    all_rounds = [(n, rid, ws) for n, rounds in levels for (_, rid, ws) in rounds]
    free_rounds = [(n, rid, ws) for n, rid, ws in all_rounds if n <= 4]

    def buildable(word):
        return any("-" in g for g in words[word]["decodableFrom"])

    free_with_words = [r for r in free_rounds if r[2]]
    free_occ = [w for _, _, ws in free_rounds for w in ws]
    all_occ = [w for _, _, ws in all_rounds for w in ws]
    buildable_occ = [w for w in all_occ if buildable(w)]
    non_buildable_occ = [w for w in all_occ if not buildable(w)]

    l9 = [(n, rid, ws) for n, rid, ws in all_rounds if rid.startswith("L9:")]
    l9_unbuildable = [w for _, _, ws in l9 for w in ws if not buildable(w)]

    groups = {}
    for word in {w for w in all_occ}:
        if word in words:
            groups.setdefault(words[word]["paiboon"], set()).add(word)
    homophones = {k: v for k, v in groups.items() if len(v) > 1}

    def shares(a, b):
        return any(ch in b for ch in a)

    def can_picture(target, pool):
        if target not in images:
            return False
        for other in pool:
            if other == target or other not in images:
                continue
            if images[other]["emoji"] == images[target]["emoji"]:
                continue
            score = (2 if shares(other, target) else 0) + (
                1 if words[other]["tone"] == words[target]["tone"] else 0
            )
            if score > 0:
                return True
        return False

    picture_occ = [
        w for _, _, ws in free_rounds for w in ws if can_picture(w, ws)
    ]

    pairs_share_round = [
        (rid, a, b)
        for a, b in (
            (sorted(v)[i], sorted(v)[j])
            for v in homophones.values()
            for i in range(len(v))
            for j in range(i + 1, len(v))
        )
        for _, rid, ws in all_rounds
        if a in ws and b in ws
    ]

    # Listen & choose (AudioChoice.tsx buildOptions): up to three distractors from
    # the round's own words, so a round of n words offers min(4, n) spellings.
    listen = {}
    for _, _, ws in free_rounds:
        n = len(set(ws))
        for w in ws:
            k = min(4, n)
            listen[k] = listen.get(k, 0) + 1

    # Picture match (steps.ts pictureDistractors, PictureChoice.tsx buildOptions).
    def picture_options(target, pool):
        ranked = []
        for other in pool:
            if other == target or other not in images:
                continue
            score = (2 if shares(other, target) else 0) + (
                1 if words[other]["tone"] == words[target]["tone"] else 0
            )
            if score > 0:
                ranked.append((score, other))
        ranked.sort(key=lambda e: -e[0])
        used = {images[target]["emoji"]}
        picked = []
        for _, other in ranked:
            if len(picked) == 3:
                break
            if images[other]["emoji"] in used:
                continue
            used.add(images[other]["emoji"])
            picked.append(other)
        return 1 + len(picked)

    picture_counts = sorted(
        picture_options(w, list(dict.fromkeys(ws)))
        for _, _, ws in free_rounds
        for w in ws
        if can_picture(w, ws)
    )

    # Typing: a blind guess of the right letter count on the round's keyboard.
    typing_odds = sorted(
        size ** len([ch for ch in w if THAI_KEY.match(ch)])
        for (number, rid), (ws, size) in round_keyboards.items()
        if number <= 4
        for w in ws
    )
    free_sizes = [size for (number, rid), (ws, size) in round_keyboards.items() if number <= 4 and ws]

    return rules_ok, {
        "keyboard_base_keys": keyboard_keys,
        "keyboard_keys_in_the_round_of_กิน": min(
            size for (number, rid), (ws, size) in round_keyboards.items() if "กิน" in ws
        ),
        "keyboard_keys_in_free_rounds_with_ปา": ",".join(
            str(size)
            for size in sorted(
                size
                for (number, rid), (ws, size) in round_keyboards.items()
                if number <= 4 and "ปา" in ws
            )
        ),
        "free_rounds_with_words": len(free_with_words),
        "free_word_in_rounds": len(free_occ),
        "free_distinct_words": len(set(free_occ)),
        "course_word_in_rounds": len(all_occ),
        "course_distinct_words": len(set(all_occ)),
        "default_build_the_word": len(buildable_occ),
        "default_not_build_the_word": len(non_buildable_occ),
        "level9_rounds": len(l9),
        "level9_tone_cards_with_defaults": len(l9_unbuildable),
        "homophone_pairs": sum(len(v) - 1 for v in homophones.values()),
        "homophone_words": sum(len(v) for v in homophones.values()),
        "picture_cards_in_free_rounds": len(picture_occ),
        "homophone_pairs_sharing_a_round": len(pairs_share_round),
        "level1_round1_buildable_words": " ".join(
            w for n, rid, ws in all_rounds if rid == "L1:R1" for w in ws if buildable(w)
        ) + " of " + str(sum(len(ws) for n, rid, ws in all_rounds if rid == "L1:R1")),
        "keyboard_keys_free_rounds_min": min(free_sizes),
        "keyboard_keys_free_rounds_max": max(free_sizes),
        "typing_odds_free_min": typing_odds[0],
        "typing_odds_free_median": typing_odds[len(typing_odds) // 2],
        "listen_choose_free_options": ",".join(
            "%d:%d" % (k, listen[k]) for k in sorted(listen, reverse=True)
        ),
        "picture_cards_free_option_counts": ",".join(str(c) for c in picture_counts),
    }


# --- the run ----------------------------------------------------------------

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recheck", action="store_true", help="re-read every page; nothing is skipped")
    args = ap.parse_args()

    with open(DATASET, encoding="utf-8") as fh:
        ds = json.load(fh)

    failures = []
    checked = 0
    cache = {}

    def load(url, kind):
        key = (url, kind)
        if key in cache:
            return cache[key]
        try:
            raw = fetch(url)
            if kind == "html":
                value = page_text(raw)
            elif kind == "json_abstract":
                index = json.loads(raw).get("abstract_inverted_index") or {}
                position = {}
                for token, places in index.items():
                    for p in places:
                        position[p] = token
                value = norm(" ".join(position[p] for p in sorted(position)))
            else:
                value = json.loads(raw)
            cache[key] = (True, value, "")
        except (urllib.error.URLError, urllib.error.HTTPError, OSError, ValueError) as exc:
            cache[key] = (False, None, "%s: %s" % (type(exc).__name__, exc))
        return cache[key]

    print("results: each named app's own page (%d rows)" % len(ds["results"]))
    for row in ds["results"]:
        label = "%s / %s" % (row["option"], row["property"])
        kind = row.get("check", "text")
        if kind == "skip":
            print("  NOT CHECKED  %s: %s" % (label, row.get("note", "")))
            continue
        ok, value, err = load(row["url"], "json" if kind.startswith("json") else "html")
        if not ok:
            print("  NOT CHECKED  %s: fetch failed (%s)" % (label, err))
            failures.append(label + ": fetch failed")
            continue
        checked += 1
        if kind == "text":
            hit = norm(row["quote"]) in value and all(
                norm(q) in value for q in row.get("also", [])
            )
            print("  %s  %s" % ("OK  " if hit else "FAIL", label))
            if not hit:
                failures.append(label + ": quote gone: %r" % row["quote"])
        elif kind == "json_absent":
            present = [
                item.get(k)
                for item in value
                for k in row["absent_keys"]
            ]
            bad = [v for v in present if v in row["absent_values"]]
            print(
                "  %s  %s (%d entries; none carries %s)"
                % ("OK  " if not bad else "FAIL", label, len(value), "/".join(row["absent_values"]))
            )
            if bad:
                failures.append(label + ": now lists %s" % bad[:3])
        else:
            failures.append(label + ": unknown check type %r" % kind)

    print("statements: what the post says about another party (%d rows)" % len(ds.get("statements", [])))
    for row in ds.get("statements", []):
        if row.get("check") == "covered_by_results":
            print("  OK    %s [%s]: its evidence is the results rows above" % (row["claim"], row["verdict"]))
            continue
        kind = "json_abstract" if row.get("check") == "json_abstract" else "html"
        ok, value, err = load(row["url"], kind)
        if not ok:
            print("  NOT CHECKED  %s: fetch failed (%s)" % (row["claim"], err))
            failures.append(row["claim"] + ": fetch failed")
            continue
        checked += 1
        hit = norm(row["quote"]) in value and all(
            norm(q) in value for q in row.get("also", [])
        )
        print("  %s  %s [%s]" % ("OK  " if hit else "FAIL", row["claim"], row["verdict"]))
        if not hit:
            failures.append(row["claim"] + ": quote gone from " + row["url"])

    print("product: Phayan's own code (%s) (%d rows)" % (REF, len(ds["product"])))
    for row in ds["product"]:
        try:
            src = read_repo(row["file"])
        except RuntimeError as exc:
            print("  NOT CHECKED  %s: %s" % (row["what"], exc))
            failures.append(row["what"] + ": file unreadable")
            continue
        checked += 1
        hit = all(norm(s) in norm(src) for s in row["expect"])
        print("  %s  %s" % ("OK  " if hit else "FAIL", row["what"]))
        if not hit:
            failures.append(row["what"] + ": code no longer says: %r" % row["expect"])

    print("price: Phayan's plans endpoint")
    plans_url = ds["price"]["url"]
    ok, value, err = load(plans_url, "json")
    if not ok:
        print("  NOT CHECKED  price: fetch failed (%s)" % err)
        failures.append("price: fetch failed")
    else:
        checked += 1
        premium = [p for p in value["plans"] if p["name"] == "Premium"][0]["pricing"]
        hit = (
            premium["monthly"] == ds["price"]["monthly"]
            and premium["annual"] == ds["price"]["annual"]
            and premium["currency"] == ds["price"]["currency"]
        )
        print(
            "  %s  %s monthly / %s annual / %s"
            % ("OK  " if hit else "FAIL", premium["monthly"], premium["annual"], premium["currency"])
        )
        if not hit:
            failures.append("price: %r" % (premium,))

    print("recount: the post's numbers re-derived from the curriculum seed")
    try:
        rules_ok, values = recount()
    except RuntimeError as exc:
        print("  NOT CHECKED  recount: %s" % exc)
        failures.append("recount: %s" % exc)
        rules_ok, values = {}, {}
    for name, ok in rules_ok.items():
        checked += 1
        print("  %s  rule: %s" % ("OK  " if ok else "FAIL", name))
        if not ok:
            failures.append("recount rule changed: " + name)
    for name, expected in ds["recount"].items():
        checked += 1
        got = values.get(name)
        hit = got == expected
        print("  %s  %s = %s%s" % ("OK  " if hit else "FAIL", name, got, "" if hit else " (post/seed says %s)" % expected))
        if not hit:
            failures.append("%s: got %r, expected %r" % (name, got, expected))

    print()
    if failures:
        print("%d checked, %d failed%s" % (checked, len(failures), " (recheck)" if args.recheck else ""))
        for f in failures:
            print("  - " + f)
        return 1
    print("%d checked, 0 failed%s" % (checked, " (recheck)" if args.recheck else ""))
    return 0


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