#!/usr/bin/env python3
"""What does a crawler that never runs JavaScript see on this page?

Usage: python render_gap_audit.py URL_OR_FILE [--expect "phrase" ...] [--agents]
--agents also compares how the server treats AI crawler user agents (run it
only on sites you own: it spoofs user agents, and edge bot rules may behave
differently for the real crawlers).
Exit code 1 if any FAIL, so it can gate a CI job.
"""
import argparse, json, re, sys
import requests
from bs4 import BeautifulSoup

MIN_WORDS = 150
AGENTS = ["GPTBot/1.1", "ClaudeBot/1.0", "PerplexityBot/1.0", "OAI-SearchBot/1.0"]
REQUIRED = {"Article": ["headline", "datePublished", "author"],
            "Product": ["name", "offers"],
            "Organization": ["name", "url"]}


def fetch(url, ua="RawHtmlAudit/1.0"):
    return requests.get(url, timeout=20, headers={"User-Agent": ua})


def load(source):
    if source.startswith("http"):
        r = fetch(source)
        r.raise_for_status()
        return r.text
    return open(source, encoding="utf-8").read()


def agent_check(url):
    base, out = fetch(url), []
    for ua in AGENTS:
        r = fetch(url, ua)
        if r.status_code != base.status_code or abs(len(r.text) - len(base.text)) > 0.3 * max(len(base.text), 1):
            out.append(("FAIL", f"{ua} got HTTP {r.status_code} ({len(r.text)} bytes); "
                                f"default client got HTTP {base.status_code} ({len(base.text)} bytes)"))
    return out


def jsonld(soup):
    blocks, errors = [], []
    for tag in soup.find_all("script", type="application/ld+json"):
        try:
            data = json.loads(tag.string or "")
        except json.JSONDecodeError as e:
            errors.append(str(e))
            continue
        for item in data if isinstance(data, list) else [data]:
            blocks.extend(item.get("@graph", [item]))
    return blocks, errors


def audit(html, expect):
    soup = BeautifulSoup(html, "html.parser")
    blocks, errors = jsonld(soup)           # parse JSON-LD before stripping scripts
    h1 = soup.h1.get_text(" ", strip=True) if soup.h1 else ""
    for tag in soup(["script", "style", "noscript", "template"]):
        tag.decompose()
    text = re.sub(r"\s+", " ", soup.get_text(" ")).strip()
    low, out = text.lower(), []

    words = len(text.split())
    if words < MIN_WORDS:
        out.append(("WARN", f"{words} words of visible text in raw HTML (possible JS shell)"))
    out += [("FAIL", f"invalid JSON-LD: {e}") for e in errors]
    out += [("FAIL", f"expected phrase missing from raw HTML: '{p}'") for p in expect if p.lower() not in low]

    for b in blocks:
        t = b.get("@type")
        t = t[0] if isinstance(t, list) else t
        out += [("WARN", f"{t} JSON-LD missing '{k}'") for k in REQUIRED.get(t, []) if k not in b]
        label = b.get("headline") or b.get("name")
        if label and h1 and label.lower() not in h1.lower() and h1.lower() not in label.lower():
            out.append(("FAIL", f"{t} says '{label}' but the H1 says '{h1}'"))
        offers = b.get("offers")
        for o in offers if isinstance(offers, list) else [offers or {}]:
            if o.get("price") and str(o["price"]) not in text:
                out.append(("FAIL", f"price {o['price']} is in JSON-LD but not in visible text"))
    return words, len(blocks), out


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("source")
    ap.add_argument("--expect", nargs="*", default=[])
    ap.add_argument("--agents", action="store_true")
    args = ap.parse_args()
    words, n_blocks, findings = audit(load(args.source), args.expect)
    if args.agents and args.source.startswith("http"):
        findings += agent_check(args.source)
    print(f"{args.source}\n  raw visible words: {words} | JSON-LD blocks: {n_blocks}")
    for level, msg in findings or [("OK", "no issues found")]:
        print(f"  [{level}] {msg}")
    sys.exit(any(level == "FAIL" for level, _ in findings))
