#!/usr/bin/env python3
"""Re-runs the source reading behind /blog/make-a-travel-map.

Every result in dataset.json carries the sentence that supports it, either on a
page (url) or in the product's own source (file). This script fetches each page
and reads each file, and reports whether that sentence is still there. Exit 0
when every readable source still says it, 1 when one no longer does.

    python3 check.py            read everything
    python3 check.py --recheck  the weekly re-read; same work here, because no
                                step of this check runs a tool for over a minute
"""

import html
import json
import re
import sys
import urllib.error
import urllib.request
import csv
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[4]
DATASET = HERE / "dataset.json"
CSV = HERE / "dataset.csv"
UA = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
    "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
)


def squeeze(text):
    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 squeeze(html.unescape(raw))


def fetch(url):
    request = urllib.request.Request(
        url,
        headers={
            "User-Agent": UA,
            "Accept-Language": "en-US,en;q=0.9",
            "Accept": "text/html,application/xhtml+xml",
        },
    )
    with urllib.request.urlopen(request, timeout=40) as response:
        charset = response.headers.get_content_charset() or "utf-8"
        return page_text(response.read().decode(charset, "replace"))


def quotes_of(result):
    return result.get("quotes") or [result["quote"]]


def main():
    results = json.loads(DATASET.read_text())["results"]
    failures = []
    checked = skipped = 0

    for result in results:
        label = "%s %s" % (result["option"], result["property"])
        needles = [squeeze(q) for q in quotes_of(result)]

        if "file" in result:
            haystack = squeeze((ROOT / result["file"]).read_text())
            missing = [q for q in needles if q not in haystack]
            if missing:
                failures.append(label)
                print("FAIL   %-32s quote gone from %s" % (label, result["file"]))
            else:
                checked += 1
                print("OK     %-32s quote found in %s" % (label, result["file"]))
            continue

        url = result["url"]
        try:
            haystack = fetch(url)
        except urllib.error.HTTPError as error:
            skipped += 1
            print("SKIP   %-32s HTTP %s from %s" % (label, error.code, url))
            continue
        except Exception as error:  # noqa: BLE001 - any transport failure is a skip
            skipped += 1
            print("SKIP   %-32s %s from %s" % (label, error.__class__.__name__, url))
            continue

        missing = [q for q in needles if q not in haystack]
        if missing:
            failures.append(label)
            print("FAIL   %-32s quote gone from %s" % (label, url))
            for q in missing:
                print("         missing: %s" % q[:120])
        else:
            checked += 1
            print("OK     %-32s quote found on %s" % (label, url))

    # The published table has to be the dataset, not a second copy of it.
    with CSV.open(newline="") as handle:
        rows = list(csv.DictReader(handle))
    by_key = {
        (r["option"], r["property"]): r["value"]
        for r in results
        if r["property"] in ("map_source", "share_methods", "viewer_sees")
    }
    csv_bad = 0
    for row in rows:
        for column in ("map_source", "share_methods", "viewer_sees"):
            published = by_key.get((row["option"], column))
            if published != row[column]:
                csv_bad += 1
                failures.append("csv %s %s" % (row["option"], column))
                print("FAIL   csv %s %s differs from dataset.json" % (row["option"], column))
    if not csv_bad:
        print("OK     dataset.csv mirrors dataset.json (%d options)" % len(rows))

    # The post's table prints the dataset values, not a second wording that can drift.
    post = ROOT / "apps/web/src/lib/blog/content-make-a-travel-map.tsx"
    body = squeeze(post.read_text().replace('{"\'"}', "'"))
    table_bad = 0
    for row in rows:
        for column in ("map_source", "share_methods", "viewer_sees"):
            if row[column] not in body:
                table_bad += 1
                failures.append("table %s %s" % (row["option"], column))
                print("FAIL   table %s %s missing from the post" % (row["option"], column))
    if not table_bad:
        print("OK     the post's table carries the dataset values (%d options)" % len(rows))

    print(
        "\n%d checked, %d not checked, %d failed"
        % (checked, skipped, len(failures))
    )
    return 1 if failures else 0


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