#!/usr/bin/env python3
"""Re-run the facebook-photos-ai-training primary-docs check.

Fetches every URL in dataset.json and reports, per claim, whether each supporting quote
still appears on the page. A claim with no quotes is reported as SKIP (not checked).
Usage: python3 check.py [path/to/dataset.json]
"""
import html
import json
import re
import subprocess
import sys
from pathlib import Path

BROWSER_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15'
# facebook.com sends its page text only in the server render it gives crawlers.
FACEBOOK_UA = 'Googlebot/2.1 (+http://www.google.com/bot.html)'
# sec.gov refuses requests that do not declare who is asking.
SEC_UA = 'Viallo blog evidence check https://www.viallo.app'


def user_agent(url):
    if '//www.facebook.com/' in url:
        return FACEBOOK_UA
    if '//www.sec.gov/' in url:
        return SEC_UA
    return BROWSER_UA


def fetch(url):
    proc = subprocess.run(
        ['curl', '-sL', '--compressed', '-m', '40', '-A', user_agent(url),
         '-H', 'Accept-Language: en-US,en', '-w', '\n%{http_code}', url],
        capture_output=True,
    )
    body, _, code = proc.stdout.decode('utf-8', 'ignore').rpartition('\n')
    return code.strip(), body


def to_text(page):
    page = re.sub(r'(?is)<(script|style)[^>]*>.*?</\1>', ' ', page)
    page = re.sub(r'<[^>]+>', ' ', page)
    return re.sub(r'\s+', ' ', html.unescape(page))


# facebook.com's help pages moved their article text out of the HTML and into a JSON tree
# inside a script (seen 2026-11-23), which to_text drops with the other scripts. These
# rebuild that text: unescape the JS string, then remove the HelpContentGalaxy node
# scaffolding so the article's own sentences run together again.
GALAXY_OPEN = re.compile(r'",?\{"type":"HelpContentGalaxy\w*","props":\{[^{}]*\},"isEagerLoaded":(?:true|false),"children":\["?'
                         r'|\{"type":"HelpContentGalaxy\w*","props":\{[^{}]*\},"isEagerLoaded":(?:true|false),"children":\["?')
GALAXY_CLOSE = re.compile(r'"?(?:\]\})+(?:,"|,|\])*')


def help_text(page):
    if 'HelpContentGalaxy' not in page:
        return ''
    s = re.sub(r'\\u([0-9a-fA-F]{4})', lambda m: chr(int(m.group(1), 16)), page.replace('\\\\', '\\'))
    s = s.replace('\\"', '"').replace('\\/', '/')
    return GALAXY_CLOSE.sub('', GALAXY_OPEN.sub('', s))


def norm(s):
    s = s.replace('’', "'").replace('‘', "'").replace('“', '"').replace('”', '"').replace('\xa0', ' ')
    return re.sub(r'\s+', ' ', s).strip().lower()


def main():
    # --recheck only re-reads the pages, which is all this check does.
    args = [a for a in sys.argv[1:] if a != '--recheck']
    path = Path(args[0]) if args else Path(__file__).with_name('dataset.json')
    data = json.loads(path.read_text())
    pages = {}
    for url in data['inputs']:
        code, body = fetch(url)
        pages[url] = (code, norm(to_text(body) + ' ' + help_text(body)))
        print(f"HTTP {code}  {url}")
    print(f"\ncheckedAt in dataset: {data['checkedAt']}\n")
    found = missing = skipped = 0
    for row in data['results']:
        for prop in data['properties']:
            cell = row[prop]
            label = f"{row['option']} / {prop}"
            if not cell['quotes']:
                skipped += 1
                print(f"SKIP     {label}: {cell['value']}")
                continue
            for q in cell['quotes']:
                status, text = pages[q['url']]
                if norm(q['quote']) in text:
                    found += 1
                    print(f"FOUND    {label} ({status})")
                else:
                    missing += 1
                    print(f"MISSING  {label} ({status}): {q['quote']!r} at {q['url']}")
    print(f"\n{found} quotes found, {missing} missing, {skipped} skipped")
    return 1 if missing else 0


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