#!/usr/bin/env python3
"""Re-run the check behind https://www.viallo.app/blog/private-photo-sharing.

Every row of dataset.json `results` names a `source`:

  page         fetch `url`, look for `quote` in the page text
  repo         read `path` in a Viallo checkout, look for `quote`
  device-test  our own Google Photos test, recorded in dataset.json; its share links were deleted
               after the measurement, so the recorded result is checked against the table
  cut, observed nothing to fetch; counted and reported

Then every row of dataset.csv is compared with dataset.json `table`.

  python3 check.py               run everything
  python3 check.py --recheck     same run: no step here takes longer than a minute

Exit 0 when every check holds, 1 otherwise. Repo rows need a Viallo checkout: the script finds
the one it sits in, or reads VIALLO_REPO; without one they are reported as skipped.
"""

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

HERE = Path(__file__).resolve().parent
DATASET = json.loads((HERE / "dataset.json").read_text(encoding="utf-8"))
UA = (
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/130.0 Safari/537.36"
)

FAILURES = []
SKIPPED = []


def find_repo():
    env = os.environ.get("VIALLO_REPO")
    if env:
        return Path(env)
    for parent in HERE.parents:
        if (parent / "packages" / "shared" / "src" / "config.ts").exists():
            return parent
    return None


REPO = find_repo()


def norm(text):
    """Tags, entities, curly quotes, dashes and whitespace are flattened before comparing."""
    text = text or ""
    text = re.sub(r"<script.*?</script>", " ", text, flags=re.S | re.I)
    text = re.sub(r"<style.*?</style>", " ", text, flags=re.S | re.I)
    text = re.sub(r"<[^>]+>", " ", text)
    text = html.unescape(text)
    for a, b in (
        ("\u2019", "'"),
        ("\u2018", "'"),
        ("\u201c", '"'),
        ("\u201d", '"'),
        ("\u2014", "-"),
        ("\u2013", "-"),
        ("\u00a0", " "),
    ):
        text = text.replace(a, b)
    return re.sub(r"\s+", " ", text).strip().lower()


def fetch(url, timeout=40, data=None, headers=None):
    hdrs = {"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"}
    hdrs.update(headers or {})
    req = urllib.request.Request(url, data=data, headers=hdrs)
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.read()


def report(ok, row, detail):
    mark = "ok  " if ok else "FAIL"
    print(f"[{mark}] {row['id']:<24} {row.get('option', '')} / {row.get('property', '')}: {detail}")
    if not ok:
        FAILURES.append(row["id"])


def check_page(row):
    try:
        body = fetch(row["url"]).decode("utf-8", "replace")
    except Exception as exc:  # noqa: BLE001 - any network failure is a failed check
        report(False, row, f"could not fetch {row['url']}: {type(exc).__name__}: {exc}")
        return
    if norm(row["quote"]) in norm(body):
        report(True, row, "quote still on the page")
    else:
        report(False, row, f"quote gone from {row['url']}")


def check_repo(row):
    if REPO is None:
        print(f"[skip] {row['id']:<24} no Viallo checkout found; set VIALLO_REPO to check {row['path']}")
        SKIPPED.append(row["id"])
        return
    path = REPO / row["path"]
    if not path.exists():
        report(False, row, f"{row['path']} no longer exists")
        return
    if norm(row["quote"]) in norm(path.read_text(encoding="utf-8")):
        report(True, row, f"line still in {row['path']}")
    else:
        report(False, row, f"\"{row['quote']}\" is no longer in {row['path']}")


def check_device_test(row):
    want = row["expect"]
    cells = next(t for t in DATASET["table"] if t["option"] == row["option"])
    size = f"{want['width']} x {want['height']}"
    bad = []
    if size not in cells["signed_out_browser_copy"]:
        bad.append(f"table copy cell does not say {size}")
    if cells["served_bytes"] != str(want["bytes"]):
        bad.append(f"table bytes {cells['served_bytes']!r} != recorded {want['bytes']}")
    if want["gps"] or "location removed" not in cells["signed_out_browser_copy"]:
        bad.append("GPS result and table disagree")
    if want["model"] not in cells["camera_make"]:
        bad.append("camera model and table disagree")
    report(not bad, row, "; ".join(bad) or f"{size}, {want['bytes']} bytes, GPS removed, {want['model']} kept (recorded 25 October 2026)")


def check_csv():
    with (HERE / "dataset.csv").open(newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    want = DATASET["table"]
    bad = [] if want else ["dataset.json has no table"]
    if len(rows) != len(want):
        bad.append(f"{len(rows)} rows in dataset.csv, {len(want)} in dataset.json table")
    for have, expected in zip(rows, want):
        for key, value in expected.items():
            if have.get(key) != value:
                bad.append(f"{expected['option']} / {key}: csv {have.get(key)!r} != json {value!r}")
    if bad:
        for line in bad:
            print(f"[FAIL] dataset.csv              {line}")
        FAILURES.append("dataset.csv")
    else:
        print(f"[ok  ] dataset.csv              {len(rows)} rows agree with dataset.json table")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--recheck", action="store_true", help="re-read every page")
    args = parser.parse_args()
    mode = "recheck" if args.recheck else "check"
    print(f"{mode} of {DATASET['slug']} (recorded {DATASET['checkedAt']})")
    for row in DATASET["results"]:
        source = row["source"]
        if source == "page":
            check_page(row)
        elif source == "repo":
            check_repo(row)
        elif source == "device-test":
            check_device_test(row)
        elif source not in ("cut", "observed"):
            report(False, row, f"unknown source {source!r}")
    cuts = sum(1 for r in DATASET["results"] if r["source"] == "cut")
    seen = sum(1 for r in DATASET["results"] if r["source"] == "observed")
    print(f"[info] {cuts} rows were cut for lack of a source and are not checked")
    print(f"[info] {seen} rows rest on what dataset.json observed records")
    check_csv()
    if SKIPPED:
        print(f"[info] {len(SKIPPED)} repo rows skipped without a Viallo checkout")
    if FAILURES:
        print(f"\n{len(FAILURES)} failing check(s): {', '.join(sorted(set(FAILURES)))}")
        return 1
    print("\nall checks hold")
    return 0


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