#!/usr/bin/env python3
"""Re-run the evidence check for the post "Do Text Messages Compress Photos?".

Two kinds of row:
  lab         a 24 MP JPEG with GPS, rebuilt from a fixed seed and pushed through the
              compression passes the post describes; dimensions, bytes, GPS survival and
              SSIM are re-measured.
  third_party a sentence the post attributes to another company; the cited page is fetched
              and the quoted sentence is searched for in its text.

dataset.csv is derived from dataset.json (lab rows, then every third-party row the post
uses) and every run checks that the two still agree.

Usage:
  python3 check.py            verify everything (lab + pages)
  python3 check.py --recheck  re-read the cited pages only, skip lab steps over a minute
  python3 check.py --build    rebuild dataset.json / dataset.csv from a fresh lab run
  python3 check.py --write-csv  rewrite dataset.csv from dataset.json

Exit 0 when every row holds, 1 otherwise.
Only the standard library, Pillow and numpy are used, and only the lab needs the last
two. --recheck skips the lab, so it runs on a bare python3. Where the lab has to run
and either is missing, the script re-runs itself under `uv run --with numpy --with
pillow` if uv is on PATH, and fails the lab otherwise. The full lab also draws its
reference image with macOS Arial, so it reproduces the recorded bytes only on a Mac.
"""

import argparse
import csv
import hashlib
import html
import io
import json
import os
import re
import sys
import time
import urllib.request
from html.parser import HTMLParser

try:
    import numpy as np
    from PIL import Image, ImageDraw, ImageFont
except ImportError:  # only the lab needs them; see lab_deps_or_reexec()
    np = Image = ImageDraw = ImageFont = None

BASE = os.path.dirname(os.path.abspath(__file__))
DATASET_JSON = os.path.join(BASE, "dataset.json")
DATASET_CSV = os.path.join(BASE, "dataset.csv")

WIDTH, HEIGHT = 6000, 4000  # 24 MP
LONG_EDGE = max(WIDTH, HEIGHT)
TOL_BYTES = 0.01     # re-encoding may shift a few bytes across Pillow builds
TOL_SSIM = 0.005
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"


# --------------------------------------------------------------------------- lab input

def build_reference_image():
    """A deterministic 24 MP scene with high-frequency detail, saved as JPEG with GPS EXIF.

    Detail matters more than subject: fine text, hard edges and noise are what a lossy
    pass destroys, so the passes differ from each other in a way a smooth photo would hide.
    """
    rng = np.random.RandomState(20261026)
    y = np.linspace(0, 1, HEIGHT, dtype=np.float32)[:, None]
    x = np.linspace(0, 1, WIDTH, dtype=np.float32)[None, :]

    sky = np.stack([
        120 + 60 * y - 0 * x,
        150 + 55 * y - 0 * x,
        200 + 40 * y - 0 * x,
    ], axis=2)
    ground = np.stack([
        60 + 30 * (1 - y) * np.ones_like(x),
        90 + 40 * (1 - y) * np.ones_like(x),
        50 + 20 * (1 - y) * np.ones_like(x),
    ], axis=2)
    horizon = 0.45
    arr = np.where((y < horizon)[:, :, None], sky, ground)

    # Fine sinusoidal texture, the stand-in for foliage and fabric.
    tex = (18 * np.sin(x * 190 + y * 40) * np.sin(y * 130)).astype(np.float32)
    arr = arr + tex[:, :, None] * 0.6

    # Sensor noise so every pass has something to smooth.
    arr = arr + rng.normal(0, 5.5, arr.shape).astype(np.float32)
    arr = np.clip(arr, 0, 255).astype(np.uint8)
    img = Image.fromarray(arr, "RGB")

    draw = ImageDraw.Draw(img)
    font_paths = [
        "/System/Library/Fonts/Supplemental/Arial.ttf",
        "/System/Library/Fonts/Helvetica.ttc",
    ]
    font_path = next((p for p in font_paths if os.path.exists(p)), None)
    if font_path is None:
        raise RuntimeError("no TrueType font found for the reference image")

    # Coloured blocks with hard edges.
    for i in range(24):
        bx = int(rng.randint(0, WIDTH - 400))
        by = int(rng.randint(0, HEIGHT - 300))
        bw, bh = int(rng.randint(120, 400)), int(rng.randint(80, 300))
        col = tuple(int(c) for c in rng.randint(20, 235, 3))
        draw.rectangle([bx, by, bx + bw, by + bh], fill=col)

    # Text at four sizes: the detail a compression pass is judged on.
    for size, step in ((52, 150), (30, 90), (18, 50), (12, 32)):
        font = ImageFont.truetype(font_path, size)
        for row in range(0, HEIGHT, step * 6):
            draw.text((40, row + size), "The quick brown fox jumps over the lazy dog 0123456789",
                      fill=(250, 250, 250), font=font)

    buf = io.BytesIO()
    exif = Image.Exif()
    exif[0x010F] = "ReferenceCam"
    exif[0x0110] = "24 MP test body"
    exif[0x0112] = 1
    exif[0x8825] = {1: "N", 2: 51.5074, 3: "W", 4: 0.1278}  # GPS IFD, London
    img.save(buf, "JPEG", quality=95, exif=exif, subsampling=0)
    return buf.getvalue()


# --------------------------------------------------------------------------- ssim

def _luma(img):
    return np.asarray(img.convert("L"), dtype=np.float32)


def _box(x, r):
    ii = np.cumsum(np.cumsum(x, axis=0), axis=1)
    ii = np.pad(ii, ((1, 0), (1, 0)))
    h, w = x.shape
    ys = np.arange(h)
    xs = np.arange(w)
    y0 = np.clip(ys - r, 0, h)
    y1 = np.clip(ys + r + 1, 0, h)
    x0 = np.clip(xs - r, 0, w)
    x1 = np.clip(xs + r + 1, 0, w)
    s = (ii[np.ix_(y1, x1)] - ii[np.ix_(y0, x1)]
         - ii[np.ix_(y1, x0)] + ii[np.ix_(y0, x0)])
    cnt = (y1 - y0)[:, None] * (x1 - x0)[None, :]
    return s / cnt


def ssim(a, b, r=4):
    """Mean SSIM over 9x9 uniform windows, computed in column strips to bound memory."""
    la, lb = _luma(a), _luma(b)
    if la.shape != lb.shape:
        raise ValueError("ssim needs equal sizes")
    h, w = la.shape
    c1, c2 = (0.01 * 255) ** 2, (0.03 * 255) ** 2
    total, count = 0.0, 0
    step = 500
    for x0 in range(0, w, step):
        x1 = min(w, x0 + step)
        core0 = max(0, x0)
        halo0 = max(0, core0 - r)
        halo1 = min(w, x1 + r)
        pa = la[:, halo0:halo1]
        pb = lb[:, halo0:halo1]
        mu_a, mu_b = _box(pa, r), _box(pb, r)
        saa = _box(pa * pa, r) - mu_a * mu_a
        sbb = _box(pb * pb, r) - mu_b * mu_b
        sab = _box(pa * pb, r) - mu_a * mu_b
        m = ((2 * mu_a * mu_b + c1) * (2 * sab + c2)) / (
            (mu_a * mu_a + mu_b * mu_b + c1) * (saa + sbb + c2))
        off0, off1 = core0 - halo0, (x1 - halo0)
        part = m[:, off0:off1]
        total += float(part.sum())
        count += part.size
    return total / count


# --------------------------------------------------------------------------- passes

def _resize_width(img, width):
    height = round(img.height * width / img.width)
    return img.resize((width, height), Image.LANCZOS)


def _resize_megapixels(img, mp):
    scale = (mp * 1_000_000 / (img.width * img.height)) ** 0.5
    return img.resize((round(img.width * scale), round(img.height * scale)), Image.LANCZOS)


def gps_present(jpeg_bytes):
    img = Image.open(io.BytesIO(jpeg_bytes))
    gps = img.getexif().get_ifd(0x8825)
    return bool(gps) and 2 in gps


PASSES = [
    ("original", "generated at 24 MP, JPEG quality 95, GPS in EXIF",
     "reference file, no pass applied", "forwarded"),
    ("resize_1024_q40", "resized to 1024 px wide, JPEG quality 40",
     "a phone-screen downscale at a low JPEG quality; no carrier or messaging app documents its settings", "forwarded"),
    ("jpeg_q40", "full resolution, JPEG quality 40", "quality level the post names", "forwarded"),
    ("jpeg_q60", "full resolution, JPEG quality 60", "quality level the post names", "forwarded"),
    ("jpeg_q75", "full resolution, JPEG quality 75", "quality level the post names", "forwarded"),
    ("resize_1080_q75", "resized to 1080 px wide, JPEG quality 75",
     "a 1080 pixel downscale at a middle JPEG quality; no messaging app documents its settings", "forwarded"),
    ("google_16mp_q85", "resized to 16 MP, JPEG quality 85",
     "Google Photos Storage saver documents the 16 MP cap, not the quality", "forwarded"),
    ("resize_1280_q85_noexif", "longest side 1280 px, JPEG quality 85, EXIF dropped",
     "a 1280 pixel downscale that drops EXIF; no messaging app documents its settings", "stripped"),
]


def run_pass(name, ref_bytes):
    ref = Image.open(io.BytesIO(ref_bytes))
    exif = ref.getexif()
    q = None
    if name == "original":
        out = ref_bytes
    elif name == "resize_1024_q40":
        q = 40
        buf = io.BytesIO(); _resize_width(ref, 1024).save(buf, "JPEG", quality=q, exif=exif, subsampling=2)
        out = buf.getvalue()
    elif name.startswith("jpeg_q"):
        q = int(name.split("q")[1])
        buf = io.BytesIO(); ref.save(buf, "JPEG", quality=q, exif=exif, subsampling=2)
        out = buf.getvalue()
    elif name == "resize_1080_q75":
        q = 75
        buf = io.BytesIO(); _resize_width(ref, 1080).save(buf, "JPEG", quality=q, exif=exif, subsampling=2)
        out = buf.getvalue()
    elif name == "google_16mp_q85":
        q = 85
        buf = io.BytesIO(); _resize_megapixels(ref, 16).save(buf, "JPEG", quality=q, exif=exif, subsampling=2)
        out = buf.getvalue()
    elif name == "resize_1280_q85_noexif":
        q = 85
        scale = 1280 / LONG_EDGE
        small = ref.resize((round(ref.width * scale), round(ref.height * scale)), Image.LANCZOS)
        buf = io.BytesIO(); small.save(buf, "JPEG", quality=q, subsampling=2)  # no exif=
        out = buf.getvalue()
    else:
        raise KeyError(name)

    img = Image.open(io.BytesIO(out))
    reference = ref if img.size == ref.size else ref.resize(img.size, Image.LANCZOS)
    # ssim_native: same pixel count on both sides, so only the re-encode counts.
    # ssim_full: the pass brought back to 6000x4000, so a resolution cut counts the way a
    # zoom or a print shows it.
    ssim_native = ssim(reference, img)
    blown = img if img.size == ref.size else img.resize(ref.size, Image.LANCZOS)
    ssim_full = ssim(ref, blown)
    return {
        "width": img.width,
        "height": img.height,
        "megapixels": round(img.width * img.height / 1_000_000, 2),
        "pixels_kept_pct": round(100 * img.width * img.height / (WIDTH * HEIGHT), 2),
        "bytes": len(out),
        "bytes_kept_pct": round(100 * len(out) / len(ref_bytes), 2),
        "jpeg_quality": q,
        "ssim_native": round(ssim_native, 4),
        "ssim_full": round(ssim_full, 4),
        "gps_survives": gps_present(out),
    }


def measure_all():
    t0 = time.time()
    ref = build_reference_image()
    rows, timings = [], {}
    for name, settings, doc, exif_policy in PASSES:
        s = time.time()
        props = run_pass(name, ref)
        timings[name] = round(time.time() - s, 1)
        rows.append({
            "option": name,
            "settings": settings,
            "documented_by": doc,
            "exif_policy": exif_policy,
            "properties": props,
            "url": f"generated:{name}.jpg",
            "quote": "",
        })
    return {
        "reference_bytes": len(ref),
        "reference_sha256": hashlib.sha256(ref).hexdigest(),
        "reference_seconds": round(time.time() - t0, 1),
        "rows": rows,
        "timings": timings,
    }


# --------------------------------------------------------------------------- pages

class _Text(HTMLParser):
    SKIP = {"script", "style", "svg", "noscript", "template"}

    def __init__(self):
        super().__init__()
        self.parts = []
        self.skip = 0

    def handle_starttag(self, tag, attrs):
        if tag in self.SKIP:
            self.skip += 1
        if tag in {"p", "div", "br", "li", "tr", "td", "th", "h1", "h2", "h3", "h4"}:
            self.parts.append(" ")

    def handle_endtag(self, tag):
        if tag in self.SKIP and self.skip:
            self.skip -= 1

    def handle_data(self, data):
        if not self.skip:
            self.parts.append(data)


def normalise(text):
    text = html.unescape(text)
    for a, b in (("’", "'"), ("‘", "'"), ("“", '"'), ("”", '"'),
                 ("\u2013", "-"), ("\u2014", "-"), (" ", " ")):
        text = text.replace(a, b)
    return re.sub(r"\s+", " ", text).strip().lower()


def page_text(url):
    req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"})
    with urllib.request.urlopen(req, timeout=45) as r:
        raw = r.read().decode("utf-8", errors="replace")
    p = _Text()
    p.feed(raw)
    return normalise("".join(p.parts))


def check_pages(rows):
    cache, failures = {}, []
    for row in rows:
        url = row["url"]
        if row.get("checker") != "page":
            print(f"  skip   {row['key']}: {row['verdict']} ({row.get('checker')})")
            continue
        if url not in cache:
            try:
                cache[url] = page_text(url)
            except Exception as exc:  # noqa: BLE001 - a blocked page is a result, not a crash
                cache[url] = exc
        page = cache[url]
        if isinstance(page, Exception):
            failures.append((row, f"page not reachable: {page}"))
            print(f"  FAIL   {row['key']}: {page}")
            continue
        if normalise(row["quote"]) in page:
            print(f"  ok     {row['key']}")
        else:
            failures.append((row, "quote not found on page"))
            print(f"  FAIL   {row['key']}: quote not found")
    return failures


# --------------------------------------------------------------------------- compare

def compare_lab(dataset, fresh):
    failures = []
    expected = {r["option"]: r["properties"] for r in dataset["results"]}
    for row in fresh["rows"]:
        name, got = row["option"], row["properties"]
        want = expected.get(name)
        if want is None:
            failures.append((name, "row missing from dataset"))
            print(f"  FAIL   {name}: row missing from dataset")
            continue
        bad = []
        for key in ("width", "height"):
            if got[key] != want[key]:
                bad.append(f"{key} {got[key]} != {want[key]}")
        if abs(got["bytes"] - want["bytes"]) > max(64, want["bytes"] * TOL_BYTES):
            bad.append(f"bytes {got['bytes']} vs {want['bytes']}")
        for key in ("ssim_native", "ssim_full"):
            if abs(got[key] - want[key]) > TOL_SSIM:
                bad.append(f"{key} {got[key]} vs {want[key]}")
        if got["gps_survives"] != want["gps_survives"]:
            bad.append(f"gps {got['gps_survives']} vs {want['gps_survives']}")
        if bad:
            failures.append((name, "; ".join(bad)))
            print(f"  FAIL   {name}: {'; '.join(bad)}")
        else:
            print(f"  ok     {name}")
    return failures


CSV_COLS = ["kind", "key", "option", "settings", "value", "output_size", "pixels_kept_pct",
            "bytes", "bytes_kept_pct", "jpeg_quality", "ssim_native", "ssim_full",
            "gps_survives", "party", "quote", "url"]


def csv_rows(dataset):
    rows = []
    for r in dataset["results"]:
        p = r["properties"]
        rows.append({
            "kind": "lab", "key": r["option"], "option": r["label"], "settings": r["settings"],
            "output_size": f"{p['width']}x{p['height']}", "pixels_kept_pct": p["pixels_kept_pct"],
            "bytes": p["bytes"], "bytes_kept_pct": p["bytes_kept_pct"],
            "jpeg_quality": "" if p["jpeg_quality"] is None else p["jpeg_quality"],
            "ssim_native": p["ssim_native"], "ssim_full": p["ssim_full"],
            "gps_survives": "yes" if p["gps_survives"] else "no", "url": r["url"],
        })
    for r in dataset["third_party"]:
        if r.get("in_post"):
            rows.append({"kind": "page" if r.get("checker") == "page" else r.get("checker", ""),
                         "key": r["key"], "option": r["option"], "value": r["value"],
                         "party": r["party"], "quote": r.get("quote", ""), "url": r["url"]})
    return [{c: str(row.get(c, "")) for c in CSV_COLS} for row in rows]


def write_csv(dataset):
    with open(DATASET_CSV, "w", encoding="utf-8", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=CSV_COLS)
        w.writeheader()
        w.writerows(csv_rows(dataset))


def check_csv(dataset):
    if not os.path.exists(DATASET_CSV):
        print("  FAIL   dataset.csv missing")
        return [("csv", "missing")]
    with open(DATASET_CSV, encoding="utf-8", newline="") as fh:
        on_disk = list(csv.DictReader(fh))
    if on_disk != csv_rows(dataset):
        print("  FAIL   dataset.csv differs from dataset.json")
        return [("csv", "differs from dataset.json")]
    print(f"  ok     {len(on_disk)} rows match dataset.json")
    return []


def write_build(dataset, fresh):
    dataset["results"] = fresh["rows"]
    dataset["reference"] = {
        "file": "generated:reference.jpg",
        "bytes": fresh["reference_bytes"],
        "sha256": fresh["reference_sha256"],
        "build_seconds": fresh["reference_seconds"],
        "description": f"{WIDTH}x{HEIGHT} JPEG, quality 95, EXIF GPS 51.5074 N 0.1278 W, fixed seed 20261026",
    }
    dataset["timings_seconds"] = fresh["timings"]
    with open(DATASET_JSON, "w", encoding="utf-8") as fh:
        json.dump(dataset, fh, indent=2, ensure_ascii=False)
        fh.write("\n")
    write_csv(dataset)


def lab_deps_or_reexec():
    """True when numpy and Pillow are importable; otherwise re-run under uv, once."""
    if np is not None:
        return True
    import shutil
    uv = shutil.which("uv")
    if uv and not os.environ.get("CHECK_PY_UNDER_UV"):
        env = dict(os.environ, CHECK_PY_UNDER_UV="1")
        sys.stdout.flush()
        os.execve(uv, [uv, "run", "--quiet", "--no-project", "--with", "numpy", "--with", "pillow",
                       "python3", os.path.abspath(__file__), *sys.argv[1:]], env)
    return False


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--recheck", action="store_true")
    ap.add_argument("--build", action="store_true")
    ap.add_argument("--write-csv", action="store_true")
    args = ap.parse_args()

    if not os.path.exists(DATASET_JSON):
        print(f"dataset.json missing at {DATASET_JSON}")
        return 1
    with open(DATASET_JSON, encoding="utf-8") as fh:
        dataset = json.load(fh)

    failures = []
    if args.write_csv:
        write_csv(dataset)
        print("wrote dataset.csv from dataset.json")
        return 0

    lab_needed = args.build or not (
        args.recheck and dataset.get("reference", {}).get("build_seconds", 0) > 60)
    if lab_needed and not lab_deps_or_reexec():
        print("lab: needs numpy and Pillow (or uv to supply them), neither is available")
        return 1

    if args.build:
        fresh = measure_all()
        write_build(dataset, fresh)
        print(f"built {len(fresh['rows'])} lab rows in {fresh['reference_seconds']:.1f}s")
        return 0

    recorded = dataset.get("reference", {}).get("build_seconds", 0)
    if args.recheck and recorded > 60:
        print(f"lab: skipped in --recheck, the rebuild as a whole takes {recorded:.0f}s, over the 60s budget")
    else:
        print("lab:")
        failures += compare_lab(dataset, measure_all())

    print("csv:")
    failures += check_csv(dataset)

    print("pages:")
    failures += check_pages(dataset["third_party"])

    print(f"\n{len(failures)} failure(s)")
    return 0 if not failures else 1


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