#!/usr/bin/env python3
"""Re-runs the guest-only-photo-album comparison check.

Every cell in dataset.csv comes from one sentence on a vendor's own help page,
or one line of Viallo's own source. This script re-reads all of them and asks
whether each supporting quote is still where the dataset says it is.

A page that cannot be fetched is reported as not checked, not as a pass.
Exit 0 when every quote is still in its source, 1 when any is gone.

    python3 check.py             # fetch every cited page and read every cited file
    python3 check.py --recheck   # the same; there is no lab step here to skip

Standard library only.
"""

from __future__ import annotations

import argparse
import gzip
import html
import json
import re
import sys
import time
import urllib.error
import urllib.request
from html.parser import HTMLParser
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATASET = HERE / "dataset.json"
# apps/web/public/blog/<slug>/ sits five levels below the repository root.
REPO = HERE.parents[4]

UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
TIMEOUT = 45
RETRIES = 3
SKIP_TAGS = {"script", "style", "noscript", "template"}

PUNCT = str.maketrans(
    {
        "“": '"',
        "”": '"',
        "‘": "'",
        "’": "'",
        "‚": "'",
        "„": '"',
        "–": "-",
        "—": "-",
        "−": "-",
        " ": " ",
        "…": "...",
    }
)


class TextExtractor(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.chunks: list[str] = []
        self.depth = 0

    def handle_starttag(self, tag, attrs):
        if tag in SKIP_TAGS:
            self.depth += 1

    def handle_endtag(self, tag):
        if tag in SKIP_TAGS and self.depth:
            self.depth -= 1

    def handle_data(self, data):
        if not self.depth and data.strip():
            self.chunks.append(data)


def normalise(text: str, page: bool = True) -> str:
    for _ in range(2):
        text = html.unescape(text)
    text = text.translate(PUNCT)
    text = re.sub(r"\s+", " ", text)
    if page:
        text = re.sub(r"\s+([.,;:!?)\]])", r"\1", text)
    return text.strip()


def page_text(raw: bytes) -> str:
    if raw[:2] == b"\x1f\x8b":
        raw = gzip.decompress(raw)
    parser = TextExtractor()
    parser.feed(raw.decode("utf-8", errors="replace"))
    return normalise(" ".join(parser.chunks))


def fetch(url: str) -> tuple[str | None, str]:
    last = ""
    for attempt in range(RETRIES):
        request = urllib.request.Request(
            url,
            headers={
                "User-Agent": UA,
                "Accept": "text/html,application/xhtml+xml",
                "Accept-Language": "en-US,en;q=0.9",
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
                return page_text(response.read()), ""
        except urllib.error.HTTPError as exc:
            last = f"HTTP {exc.code}"
            if exc.code in (403, 404, 410):
                break
        except Exception as exc:  # any transport failure is one report
            last = f"{type(exc).__name__}: {exc}"
        if attempt + 1 < RETRIES:
            time.sleep(2 * (attempt + 1))
    return None, last or "unreachable"


def read_file(spec: str) -> tuple[str | None, str]:
    path = REPO / spec
    try:
        return normalise(path.read_text(encoding="utf-8"), page=False), ""
    except OSError as exc:
        return None, f"{type(exc).__name__}: {exc}"


def resolve(source: str) -> tuple[str | None, str]:
    if source.startswith("repo:"):
        return read_file(source[len("repo:") :])
    return fetch(source)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--recheck",
        action="store_true",
        help="re-read every cited source; there is no lab step here to skip",
    )
    parser.parse_args()

    data = json.loads(DATASET.read_text(encoding="utf-8"))
    cache: dict[str, tuple[str | None, str]] = {}
    failures: list[str] = []
    checked = 0

    print(f"guest-only-photo-album, checked {data['checkedAt']}")

    for row in data["results"]:
        for prop, cell in row["properties"].items():
            source = cell["url"]
            label = f"{row['option']} / {prop}"
            if source not in cache:
                cache[source] = resolve(source)
            text, error = cache[source]
            if text is None:
                failures.append(f"{label}: source not read ({error}) {source}")
                print(f"NOT CHECKED  {label}  <- {error}")
                continue
            checked += 1
            if normalise(cell["quote"], page=not source.startswith("repo:")) in text:
                print(f"ok           {label}")
            else:
                failures.append(f"{label}: quote gone from {source}")
                print(f"MISSING      {label}  <- {source}")

    print()
    print(f"{checked} quotes checked across {len(cache)} sources on {data['checkedAt']}")
    if failures:
        print(f"{len(failures)} failed:")
        for line in failures:
            print(f"  - {line}")
        return 1
    print("every quote is still in the source it cites")
    return 0


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