#!/usr/bin/env python3
"""Re-check every sentence the dataset rests on.

Fetches each URL in dataset.json, strips tags, normalises whitespace and
typographic quotes, and reports per row whether the quoted sentence is still
on the page. There are no lab steps, so --recheck does the same thing as a
plain run; the flag is accepted for the contract in evidence.md.

Exit 0 when every quote is found, 1 otherwise.
"""

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

HERE = Path(__file__).resolve().parent
DATASET = HERE / "dataset.json"
UA = "Mozilla/5.0"
TIMEOUT = 40

QUOTES = str.maketrans({
    "\u2018": "'", "\u2019": "'", "\u201a": "'", "\u201b": "'",
    "\u201c": '"', "\u201d": '"', "\u201e": '"', "\u201f": '"',
    "\u2013": "-", "\u2014": "-", "\u2212": "-",
    "\u00a0": " ", "\u2009": " ", "\u202f": " ",
    "\u00ad": "", "\u200b": "", "\u200e": "", "\u200f": "",
})


class TextOnly(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.chunks = []
        self.skip = 0

    def handle_starttag(self, tag, attrs):
        if tag in ("script", "style", "noscript", "template"):
            self.skip += 1

    def handle_endtag(self, tag):
        if tag in ("script", "style", "noscript", "template") and self.skip:
            self.skip -= 1

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


def normalise(text):
    text = html.unescape(text)
    text = text.translate(QUOTES)
    return " ".join(text.split())


def page_text(raw):
    parser = TextOnly()
    parser.feed(raw)
    return normalise("".join(parser.chunks))


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "en-US,en"})
    with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
        charset = response.headers.get_content_charset() or "utf-8"
        return response.read().decode(charset, errors="replace")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--recheck", action="store_true",
                        help="re-read the cited pages; no lab step exists to skip")
    args = parser.parse_args()

    dataset = json.loads(DATASET.read_text(encoding="utf-8"))
    results = dataset["results"]

    pages = {}
    fetch_errors = {}
    for url in sorted({row["url"] for row in results}):
        try:
            pages[url] = page_text(fetch(url))
        except (urllib.error.URLError, urllib.error.HTTPError, OSError) as error:
            fetch_errors[url] = f"{type(error).__name__}: {error}"

    failures = 0
    for row in results:
        url = row["url"]
        quote = normalise(row["quote"])
        if url in fetch_errors:
            print(f"FAIL {row['id']}: page not fetched ({fetch_errors[url]})")
            failures += 1
        elif quote in pages[url]:
            print(f"PASS {row['id']}: {row['property']} = {row['value']}")
        else:
            print(f"FAIL {row['id']}: quote not found on {url}")
            print(f"     looked for: {quote[:160]}")
            failures += 1

    total = len(results)
    mode = "recheck" if args.recheck else "check"
    print(f"\n{mode}: {total - failures}/{total} rows hold, dataset checked {dataset['checkedAt']} ({dataset['method']})")
    return 0 if failures == 0 else 1


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