#!/usr/bin/env python3
"""Re-run the evidence check for the Phayan post thai-months-and-dates.

Every row of dataset.json is asserted against the page it was taken from:
the Royal Institute Dictionary entry for each of the twelve month names
and for ปีงบประมาณ, พุทธศักราช and คริสต์ศักราช, the Thai and English
Wikipedia solar-calendar articles, Thai PBS, Google Translate, Ling, Anki and the
Phayan source tree.

Exit 0 when every quote is still on its page and every measurement still
holds, 1 otherwise. `--recheck` is accepted for the weekly sweep; this
check has no lab step, so there is nothing for it to skip.

Standard library only.
"""

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

BASE = os.path.dirname(os.path.abspath(__file__))
DATASET = os.path.join(BASE, "dataset.json")
# apps/web/public/blog/<slug>/check.py sits five levels below the repository root
PHAYAN = os.environ.get("PHAYAN_REPO") or os.path.abspath(os.path.join(BASE, *[".."] * 5))
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"

results = []


def record(name, passed, detail=""):
    results.append((name, passed, detail))
    mark = "PASS" if passed else "FAIL"
    line = "%-4s %s" % (mark, name)
    if detail and not passed:
        line += "\n       " + detail.replace("\n", "\n       ")
    print(line)


def norm(text, strip_tags=True):
    """Collapse whitespace, HTML entities and tag boundaries so a quote can be
    compared against a rendered page. Source code and wikitext pass
    strip_tags=False: `a < b` far above an arrow `=>` is not a tag."""
    text = html.unescape(text)
    text = unicodedata.normalize("NFC", text)
    text = text.replace(" ", " ").replace("​", "")
    if strip_tags:
        text = re.sub(r"<[^>]+>", " ", text)
    text = re.sub(r"\s+", " ", text)
    return text.strip()


def request(url, data=None, timeout=60):
    body = None
    if data is not None:
        body = urllib.parse.urlencode(data).encode("utf-8")
    req = urllib.request.Request(url, data=body, headers={"User-Agent": UA})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.getcode(), resp.read().decode("utf-8", "replace")


def get(url):
    return request(url)


def show_around(text, needle, width=120):
    i = text.find(needle[:40])
    if i < 0:
        return "not found; page begins: " + text[:width]
    return "near: " + text[max(0, i - width):i + len(needle) + width]


def check_quote(label, page, quote, hint=""):
    found = norm(quote) in page
    detail = ""
    if not found:
        detail = "quote gone from page\n  quote: %r\n  %s" % (
            norm(quote)[:200],
            show_around(page, norm(quote)),
        )
    record(label, found, detail)
    return found


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recheck", action="store_true",
                    help="re-read every page (this check has no lab step to skip)")
    args = ap.parse_args()

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

    inputs = {i["id"]: i for i in ds["inputs"]}
    print("checkedAt in dataset: %s | recheck: %s" % (ds["checkedAt"], args.recheck))
    print("")

    # ---- 1. Royal Institute Dictionary, one POST lookup per month ----------
    print("== Royal Institute Dictionary (primary source)")
    d = inputs["royal-institute-dictionary"]
    months = ds["results"]["months"]
    for m in months:
        thai = m["thai"]
        fields = dict(d["post_fields"])
        fields["word"] = thai
        try:
            _, raw = request(d["url"], data=fields)
        except Exception as exc:  # network or HTTP failure
            record("%s %s reachable" % (m["option"], thai), False, "fetch failed: %s" % exc)
            continue
        page = norm(raw)
        ok = page != ""
        record("%s %s reachable" % (m["option"], thai), ok,
               "" if ok else "empty body; the endpoint answers POST only")
        if not ok:
            continue
        days = m["properties"]["days"]
        check_quote("%s %s days: %s" % (m["option"], thai, days["value"]), page, days["quote"])
        root = m["properties"]["root"]
        check_quote("%s %s root: %s" % (m["option"], thai, root["value"]), page, root["quote"])
        headword = page.find(thai)
        record("%s %s headword present" % (m["option"], thai), headword >= 0)

    # ---- 2. The rule the post draws from those entries ---------------------
    print("")
    print("== The ending rule, recomputed from the dataset")
    khom = [m for m in months if m["ending"] == "-คม"]
    yon = [m for m in months if m["ending"] == "-ยน"]
    phan = [m for m in months if m["ending"] == "-พันธ์"]
    rule = ds["results"]["rule"]["totals"]
    record("7 months end -คม", len(khom) == rule["khom_months"],
           "found %d" % len(khom))
    record("every -คม month is 31 days",
           all(m["days"] == "31" for m in khom),
           "offenders: %s" % [m["option"] for m in khom if m["days"] != "31"])
    record("4 months end -ยน", len(yon) == rule["yon_months"],
           "found %d" % len(yon))
    record("every -ยน month is 30 days",
           all(m["days"] == "30" for m in yon),
           "offenders: %s" % [m["option"] for m in yon if m["days"] != "30"])
    record("-พันธ์ is February alone",
           len(phan) == 1 and phan[0]["option"] == "February",
           "found %s" % [m["option"] for m in phan])
    total = sum(31 for _ in khom) + sum(30 for _ in yon) + 28
    record("the twelve months total %d days" % rule["days_in_year"],
           total == rule["days_in_year"], "summed %d" % total)
    record("abbreviation second letter matches the ending",
           all(m["abbreviation_second_letter"] == m["ending"][1] for m in months),
           "offenders: %s" % [m["option"] for m in months
                              if m["abbreviation_second_letter"] != m["ending"][1]])
    record("abbreviation second letter is one of ค ย พ",
           all(m["abbreviation_second_letter"] in "คยพ" for m in months))

    # ---- 3. Thai Wikipedia table (independent check of abbreviations) ------
    print("")
    print("== Thai Wikipedia, ปฏิทินสุริยคติไทย")
    w = inputs["th-wikipedia-solar-calendar"]
    try:
        _, raw = get(w["url"])
        wiki = norm(raw)
        record("Thai Wikipedia reachable", wiki != "")
        for m in months:
            check_quote("%s %s abbreviation row" % (m["option"], m["abbreviation"]),
                        wiki, m["properties"]["abbreviation"]["quote"])
        check_quote("the article states the -คม / -ยน split",
                    wiki, ds["results"]["suffix_rule_source"]["quote"])
    except Exception as exc:
        record("Thai Wikipedia reachable", False, "fetch failed: %s" % exc)

    # ---- 3b. English Wikipedia: Sanskrit word, sign, the 543 offset --------
    print("")
    print("== English Wikipedia, Thai solar calendar")
    e = inputs["en-wikipedia-thai-solar-calendar"]
    try:
        _, raw = get(e["url"])
        en = norm(raw)
        record("English Wikipedia reachable", en != "")
        for m in months:
            check_quote("%s sign %s, word %s" % (m["option"], m["zodiac_sign"], m["sanskrit_word"]),
                        en, m["properties"]["zodiac_sign"]["quote"])
        for key in ("pre_1941_offset", "government_calendar", "ending_meaning_en"):
            check_quote("%s: %s" % (key, ds["results"][key]["value"]), en, ds["results"][key]["quote"])
    except Exception as exc:
        record("English Wikipedia reachable", False, "fetch failed: %s" % exc)

    # ---- 3c. Royal Institute: budget year and the two eras -----------------
    print("")
    print("== Royal Institute Dictionary, the year")
    for key in ("budget_year", "buddhist_era", "common_era"):
        r = ds["results"][key]
        fields = dict(d["post_fields"])
        fields["word"] = r["word"]
        try:
            _, raw = request(d["url"], data=fields)
        except Exception as exc:
            record("%s reachable" % r["word"], False, "fetch failed: %s" % exc)
            continue
        check_quote("%s: %s" % (r["word"], r["value"]), norm(raw), r["quote"])

    # ---- 4. Thai PBS, the dated source for 1889 ----------------------------
    print("")
    print("== Thai PBS, 1 September 2023")
    pbs = inputs["thai-pbs-month-names"]
    try:
        _, raw = get(pbs["url"])
        pbs_text = norm(raw)
        record("Thai PBS reachable", pbs_text != "")
        for q in ds["results"]["adoption_year"]["quotes"]:
            check_quote("adoption year: %s" % q["quote"][:48], pbs_text, q["quote"])
        for q in ds["results"]["root_meaning"]["quotes"]:
            if q["source"] == "thai-pbs-month-names":
                check_quote("root meaning: %s" % q["quote"][:48], pbs_text, q["quote"])
    except Exception as exc:
        record("Thai PBS reachable", False, "fetch failed: %s" % exc)

    # ---- 5. Google Translate, the post's third-party claim -----------------
    print("")
    print("== Google Translate, one Thai date per month")
    gt = inputs["google-translate"]
    gt_base = gt["url"].split("?")[0]
    for row in ds["results"]["google_translate"]["rows"]:
        q = urllib.parse.quote(row["input"])
        url = gt_base + "?" + urllib.parse.urlencode(
            {"client": "gtx", "sl": "th", "tl": "en", "dt": "t", "q": row["input"]})
        url = url.replace("+", "%20")
        try:
            _, raw = get(url)
            payload = json.loads(raw)
            out = "".join(seg[0] for seg in payload[0] if seg[0])
        except Exception as exc:
            record("translate %s" % row["input"], False, "fetch failed: %s" % exc)
            continue
        converted = "2026" in out and "2569" not in out
        record("translate %s -> %s" % (row["input"], row["output"]),
               converted and out.strip() == row["output"].strip(),
               "got %r (expected %r)" % (out, row["output"]))

    # ---- 6. Ling ----------------------------------------------------------
    print("")
    print("== Ling App, Thai months article")
    ling = inputs["ling-thai-months"]
    try:
        _, raw = get(ling["url"])
        ling_text = norm(raw)
        record("Ling reachable", ling_text != "")
        check_quote("Ling's month table is word, abbreviation, pronunciation only",
                    ling_text, ds["results"]["ling"]["quote"])
        for term in ["Sanskrit", "zodiac", "31 days", "30 days", "suffix"]:
            record("Ling states no %r" % term, term not in ling_text)
    except Exception as exc:
        record("Ling reachable", False, "fetch failed: %s" % exc)

    # ---- 6b. Anki, what it says about itself ------------------------------
    print("")
    print("== Anki home page")
    a = ds["results"]["anki"]
    try:
        _, raw = get(a["url"])
        check_quote("Anki describes itself as a flashcard program", norm(raw), a["quote"])
    except Exception as exc:
        record("Anki reachable", False, "fetch failed: %s" % exc)

    # ---- 7. Phayan product facts -----------------------------------------
    print("")
    print("== Phayan product facts, read from %s" % PHAYAN)
    for claim in ds["results"]["phayan_product"]:
        try:
            with open(os.path.join(PHAYAN, claim["file"]), encoding="utf-8") as fh:
                src = fh.read()
        except OSError as exc:
            record("%s readable" % claim["file"], False,
                   "%s (outside the repository, set PHAYAN_REPO)" % exc)
            continue
        src_n = norm(src, strip_tags=False)
        for q in claim["quotes"]:
            check_quote("%s: %s" % (claim["claim"][:44], q[:40]), src_n, q,
                        hint=claim["file"])

    # ---- summary ----------------------------------------------------------
    failed = [r for r in results if not r[1]]
    print("")
    print("%d checks, %d passed, %d failed" % (len(results), len(results) - len(failed), len(failed)))
    return 1 if failed else 0


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