#!/usr/bin/env python3
"""aeo_check: a free, local check of how readable one web page and its site are to search and AI answer engines.

Checks: HTTPS and status, title and description, canonical, headings, structured data (JSON-LD), robots.txt rules
for common AI crawlers, sitemap, llms.txt, basic content signals. Makes only normal GET requests to the site you name
(the page, /robots.txt, the sitemap, /llms.txt). Python 3.8+, standard library only. MIT licence.

Usage:  python3 aeo_check.py https://example.com/page
        python3 aeo_check.py https://example.com --json
This is a readiness check, not a ranking prediction. Nobody can promise that an AI engine will cite a page.
"""
import json, re, sys, time, urllib.request, urllib.parse, urllib.error, html as htmllib

UA = "hackerdb-aeo-check/1.0 (+https://hackerdb-agents.derrickb.workers.dev/tools/ai-search-check)"
# user-agent token, owner, purpose (names change: verify against each vendor's documentation)
AI_BOTS = [
 ("OAI-SearchBot", "OpenAI", "search"), ("ChatGPT-User", "OpenAI", "user-requested fetch"), ("GPTBot", "OpenAI", "training"),
 ("Claude-SearchBot", "Anthropic", "search"), ("Claude-User", "Anthropic", "user-requested fetch"), ("ClaudeBot", "Anthropic", "training"),
 ("PerplexityBot", "Perplexity", "search index"), ("Perplexity-User", "Perplexity", "user-requested fetch"),
 ("Googlebot", "Google", "search (also feeds AI features in Search)"), ("Google-Extended", "Google", "AI training/grounding control token"),
 ("Applebot", "Apple", "search"), ("Applebot-Extended", "Apple", "AI training control token"),
 ("CCBot", "Common Crawl", "public dataset"), ("Bingbot", "Microsoft", "search (feeds Copilot)"),
]

def fetch(url, limit=1_500_000, timeout=12):
    req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "text/html,text/plain,application/xml;q=0.9,*/*;q=0.5"})
    t0 = time.time()
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            body = r.read(limit)
            return dict(ok=True, status=r.status, url=r.geturl(), headers={k.lower(): v for k, v in r.headers.items()}, body=body.decode("utf-8", "replace"), ms=int((time.time() - t0) * 1000))
    except urllib.error.HTTPError as e:
        return dict(ok=False, status=e.code, url=url, headers={}, body="", ms=int((time.time() - t0) * 1000))
    except Exception as e:
        return dict(ok=False, status=0, url=url, headers={}, body="", ms=int((time.time() - t0) * 1000), err=e.__class__.__name__)

def parse_robots(txt):
    groups, cur, agents = [], None, []
    sitemaps = []
    for raw in txt.splitlines():
        line = raw.split("#", 1)[0].strip()
        if ":" not in line: continue
        k, v = [x.strip() for x in line.split(":", 1)]
        k = k.lower()
        if k == "user-agent":
            if cur is None or cur["rules"]:
                cur = dict(agents=[], rules=[]); groups.append(cur)
            cur["agents"].append(v.lower())
        elif k in ("allow", "disallow") and cur is not None:
            cur["rules"].append((k, v))
        elif k == "sitemap":
            sitemaps.append(v)
    return groups, sitemaps

def robots_allows(groups, agent, path="/"):
    a = agent.lower()
    chosen = None
    for g in groups:
        if a in g["agents"]: chosen = g; break
    if chosen is None:
        for g in groups:
            if "*" in g["agents"]: chosen = g; break
    if chosen is None: return True, "no rule (allowed by default)"
    best, verdict = -1, True
    for k, v in chosen["rules"]:
        if v == "" and k == "disallow": continue
        pat = re.escape(v).replace(r"\*", ".*").replace(r"\$", "$")
        if re.match(pat, path):
            ln = len(v)
            if ln > best or (ln == best and k == "allow"):
                best, verdict = ln, (k == "allow")
    which = "agent group" if a in chosen["agents"] else "* group"
    return verdict, ("allowed" if verdict else "blocked") + " by " + which

def strip_tags(h):
    h = re.sub(r"(?is)<(script|style|noscript|template)[^>]*>.*?</\1>", " ", h)
    return re.sub(r"\s+", " ", htmllib.unescape(re.sub(r"<[^>]+>", " ", h))).strip()

def attr(tag, name):
    m = re.search(r'\b%s\s*=\s*("([^"]*)"|\'([^\']*)\'|([^\s>]+))' % name, tag, re.I)
    return htmllib.unescape(next((g for g in m.groups()[1:] if g is not None), "")) if m else None

def jsonld_types(h):
    types, bad = [], 0
    for m in re.finditer(r'(?is)<script[^>]+type\s*=\s*["\']application/ld\+json["\'][^>]*>(.*?)</script>', h):
        try:
            data = json.loads(m.group(1))
        except Exception:
            bad += 1; continue
        stack = [data]
        while stack:
            x = stack.pop()
            if isinstance(x, list): stack += x
            elif isinstance(x, dict):
                t = x.get("@type")
                if isinstance(t, str): types.append(t)
                elif isinstance(t, list): types += [str(i) for i in t]
                stack += [v for v in x.values() if isinstance(v, (dict, list))]
    return sorted(set(types)), bad

def analyze(url):
    u = urllib.parse.urlparse(url if "://" in url else "https://" + url)
    if u.scheme not in ("http", "https") or not u.hostname:
        raise SystemExit("Give a full http(s) URL.")
    base = "%s://%s" % (u.scheme, u.netloc)
    checks = []
    def add(id, label, weight, passed, detail, fix=""):
        checks.append(dict(id=id, label=label, weight=weight, passed=bool(passed), detail=detail, fix=fix))
    page = fetch(u.geturl())
    if not page["ok"]:
        return dict(url=u.geturl(), error="Could not fetch the page (status %s %s)." % (page["status"], page.get("err", "")), checks=[], score=0)
    h = page["body"]
    final = urllib.parse.urlparse(page["url"])
    add("https", "Served over HTTPS", 5, final.scheme == "https", final.scheme, "Serve the site over HTTPS and redirect http to https.")
    add("status", "Page returns 200", 5, page["status"] == 200, str(page["status"]), "Fix errors and redirect chains so the page returns 200.")
    xr = page["headers"].get("x-robots-tag", "").lower()
    meta_robots = " ".join(attr(t, "content") or "" for t in re.findall(r'(?i)<meta[^>]+name\s*=\s*["\']robots["\'][^>]*>', h)).lower()
    noindex = "noindex" in xr or "noindex" in meta_robots
    add("indexable", "Page is not set to noindex", 10, not noindex, "noindex found" if noindex else "indexable", "Remove noindex (meta robots or X-Robots-Tag) if you want this page found.")
    tm = re.search(r"(?is)<title[^>]*>(.*?)</title>", h); title = strip_tags(tm.group(1)) if tm else ""
    add("title", "Title present, 15-65 characters", 6, 15 <= len(title) <= 65, "%d chars: %s" % (len(title), title[:70]), "Write a specific title of about 30-60 characters that names the topic.")
    md = [attr(t, "content") for t in re.findall(r'(?i)<meta[^>]+name\s*=\s*["\']description["\'][^>]*>', h)]
    d = (md[0] or "") if md else ""
    add("desc", "Meta description present, 70-170 characters", 5, 70 <= len(d) <= 170, "%d chars" % len(d), "Add a plain-language summary of about 120-160 characters.")
    canon = [attr(t, "href") for t in re.findall(r'(?i)<link[^>]+rel\s*=\s*["\']canonical["\'][^>]*>', h)]
    add("canonical", "Canonical URL declared", 5, bool(canon and canon[0]), (canon[0] if canon and canon[0] else "missing"), "Add <link rel=\"canonical\"> with the preferred absolute URL.")
    h1s = re.findall(r"(?is)<h1[^>]*>(.*?)</h1>", h)
    add("h1", "Exactly one H1", 5, len(h1s) == 1, "%d found" % len(h1s), "Use one H1 that states the page topic.")
    h2s = re.findall(r"(?is)<h2[^>]*>", h)
    add("h2", "At least two H2 sections", 3, len(h2s) >= 2, "%d found" % len(h2s), "Break the page into sections with descriptive H2 headings (ideally phrased as questions or clear topics).")
    lang = re.search(r"(?is)<html[^>]+lang\s*=", h)
    add("lang", "html lang attribute", 2, bool(lang), "present" if lang else "missing", "Add lang=\"en\" (or your language) to <html>.")
    og = len(re.findall(r'(?i)<meta[^>]+property\s*=\s*["\']og:(title|description|image)["\']', h))
    add("og", "Open Graph title, description, image", 3, og >= 3, "%d of 3" % min(og, 3), "Add og:title, og:description and og:image for link previews.")
    types, bad = jsonld_types(h)
    add("jsonld", "Valid JSON-LD structured data present", 8, bool(types) and bad == 0, (", ".join(types) or "none") + ("; %d block(s) invalid JSON" % bad if bad else ""), "Add JSON-LD for the page type (Organization/WebSite, Article, Product, FAQPage as fits). Validate it.")
    text = strip_tags(h); words = len(text.split())
    add("content", "Enough readable text (300+ words)", 6, words >= 300, "%d words" % words, "Answer the topic fully in text; do not hide content behind scripts or images.")
    imgs = re.findall(r"(?is)<img\b[^>]*>", h)
    noalt = [i for i in imgs if not (attr(i, "alt") or "").strip()]
    add("alt", "Images have alt text (80%+)", 2, (not imgs) or (len(imgs) - len(noalt)) / len(imgs) >= 0.8, "%d of %d have alt" % (len(imgs) - len(noalt), len(imgs)), "Describe meaningful images in alt text.")
    js_heavy = words < 100 and len(re.findall(r"(?i)<script", h)) >= 3
    add("ssr", "Content is in the HTML (not only built by scripts)", 6, not js_heavy, "little text in raw HTML with several scripts" if js_heavy else "text present in raw HTML", "Server-render or pre-render key content: many AI crawlers do not run JavaScript.")
    # robots.txt
    rb = fetch(base + "/robots.txt", 300_000)
    groups, sitemaps = (parse_robots(rb["body"]) if rb["ok"] else ([], []))
    path = final.path or "/"
    bots = []
    for tok, owner, purpose in AI_BOTS:
        ok, why = robots_allows(groups, tok, path)
        bots.append(dict(bot=tok, owner=owner, purpose=purpose, allowed=ok, why=why))
    search_bots = [b for b in bots if b["bot"] in ("OAI-SearchBot", "Claude-SearchBot", "PerplexityBot", "Googlebot", "Bingbot")]
    blocked_search = [b["bot"] for b in search_bots if not b["allowed"]]
    add("robots", "robots.txt reachable", 3, rb["ok"], str(rb["status"]), "Publish /robots.txt (even a minimal one that lists your sitemap).")
    add("ai_search", "Search-type AI and search crawlers allowed", 12, not blocked_search, ("blocked: " + ", ".join(blocked_search)) if blocked_search else "allowed", "If you want citations in AI answers, allow the search crawlers. Block only training crawlers if that is your policy.")
    # sitemap
    sm_url = sitemaps[0] if sitemaps else base + "/sitemap.xml"
    sm = fetch(sm_url, 400_000)
    sm_ok = sm["ok"] and ("<urlset" in sm["body"] or "<sitemapindex" in sm["body"])
    add("sitemap", "XML sitemap found", 6, sm_ok, sm_url if sm_ok else "not found", "Publish /sitemap.xml and list it in robots.txt with a Sitemap: line.")
    add("sitemap_robots", "Sitemap listed in robots.txt", 2, bool(sitemaps), sitemaps[0] if sitemaps else "no Sitemap: line", "Add a Sitemap: line to robots.txt.")
    # llms.txt
    ll = fetch(base + "/llms.txt", 200_000)
    llms_ok = ll["ok"] and ll["body"].lstrip().startswith("#")
    add("llms", "llms.txt present (proposed standard; low cost)", 4, llms_ok, "found" if llms_ok else "not found", "Add /llms.txt: a Markdown summary and links to your best pages. Note: major engines have not confirmed they use it.")
    total = sum(c["weight"] for c in checks); got = sum(c["weight"] for c in checks if c["passed"])
    return dict(url=page["url"], fetched_ms=page["ms"], score=round(100 * got / total), checks=checks, ai_bots=bots, title=title, words=words, jsonld_types=types)

def main():
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    if not args:
        print(__doc__); return 2
    r = analyze(args[0])
    if "--json" in sys.argv:
        print(json.dumps(r, indent=2)); return 0
    if r.get("error"): print(r["error"]); return 1
    print("AI search readiness for %s\nScore: %d/100 (weights are the author's judgement, not a ranking factor list)\n" % (r["url"], r["score"]))
    for c in r["checks"]:
        print("[%s] %s: %s" % ("PASS" if c["passed"] else "FAIL", c["label"], c["detail"]))
        if not c["passed"]: print("       fix: " + c["fix"])
    print("\nAI crawler rules in robots.txt for this path:")
    for b in r["ai_bots"]: print("  %-18s %-12s %-8s %s" % (b["bot"], b["owner"], "allowed" if b["allowed"] else "BLOCKED", b["purpose"]))
    print("\nThis is a readiness check, not a promise of rankings or citations.")
    return 0
if __name__ == "__main__":
    sys.exit(main())
