---
type: "Source File"
title: "from __future__ import annotations"
description: "from __future__ import annotations import argparse import hashlib import html import ipaddress import json import os import re import socket import threading import time from concurrent.futures import."
resource: "https://seo.copecheck.com"
tags: ["copecheck", "seo", "source-file", "py"]
timestamp: "2026-09-26T08:20:53Z"
site: "seo"
source_path: "copecheck-seo/server.py"
---

# from __future__ import annotations

Source path: `copecheck-seo/server.py`  
Index snapshot generated: `2026-11-24T13:27:52Z`  
File modified: `2026-09-26T08:20:53Z`

```py
from __future__ import annotations

import argparse
import hashlib
import html
import ipaddress
import json
import os
import re
import socket
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from email.utils import format_datetime
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, quote_plus, urlencode, urljoin, urlparse
from urllib.request import Request, urlopen


BASE = Path(__file__).resolve().parent
DATA_DIR = BASE / "data"
SITE_REGISTRY_FILE = DATA_DIR / "network-sites.json"
PUBLIC_BASE = os.getenv("COPECHECK_SEO_PUBLIC_BASE", "https://seo.copecheck.com").rstrip("/")
CACHE_SECONDS = int(os.getenv("COPECHECK_SEO_CACHE_SECONDS", "900"))
FETCH_TIMEOUT = float(os.getenv("COPECHECK_SEO_FETCH_TIMEOUT", "5"))
SNAPSHOT_LOCK = threading.Lock()
SNAPSHOT_CACHE: dict[str, Any] = {"expires": 0, "data": None}
SNAPSHOT_REFRESHING = False
AUDIT_LOCK = threading.Lock()
AUDIT_RATE_STORE: dict[str, list[float]] = {}
AUDIT_RATE_WINDOW = 3600
AUDIT_RATE_LIMIT = 18
AUDIT_BODY_LIMIT = 20_000
FEEDBACK_FILE = DATA_DIR / "seo-feedback.jsonl"
FEEDBACK_LOCK = threading.Lock()
FEEDBACK_RATE_STORE: dict[str, list[float]] = {}
FEEDBACK_RATE_WINDOW = 3600
FEEDBACK_RATE_LIMIT = 24
FEEDBACK_BODY_LIMIT = 12_000
AUDIT_SEVERITY_WEIGHT = {
    "critical": 18,
    "high": 10,
    "medium": 6,
    "low": 3,
}
AI_CRAWLERS = [
    "GPTBot",
    "OAI-SearchBot",
    "ChatGPT-User",
    "ClaudeBot",
    "Claude-SearchBot",
    "anthropic-ai",
    "PerplexityBot",
    "Google-Extended",
    "Applebot-Extended",
]
AI_DISCOVERY_CRAWLERS = {"GPTBot", "OAI-SearchBot", "ChatGPT-User", "ClaudeBot", "Claude-SearchBot", "anthropic-ai", "PerplexityBot"}
ROBOTS_CONTENT_SIGNAL_FIELDS = ("search", "ai-input", "ai-train")
CLOUDFLARE_ROBOTS_MARKERS = (
    "cloudflare managed",
    "ai crawl control",
    "content signal",
    "content-signal",
)
GOOGLE_AI_GUIDE_URL = "https://developers.google.com/search/docs/fundamentals/ai-optimization-guide"
LIGHTHOUSE_AGENTIC_SCORING_URL = "https://developer.chrome.com/docs/lighthouse/agentic-browsing/scoring"
LIGHTHOUSE_LLMS_TXT_URL = "https://developer.chrome.com/docs/lighthouse/agentic-browsing/llms-txt"
LIGHTHOUSE_WEBMCP_TOOLS_URL = "https://developer.chrome.com/docs/lighthouse/agentic-browsing/registered-webmcp-tools"
STOP_WORDS = {
    "about",
    "after",
    "again",
    "against",
    "also",
    "because",
    "before",
    "being",
    "between",
    "from",
    "have",
    "into",
    "more",
    "most",
    "over",
    "that",
    "their",
    "then",
    "there",
    "these",
    "this",
    "with",
    "your",
}

TUNNEL_TARGET = "6b861c04-84fb-48ea-88c8-d72feaae48c8.cfargotunnel.com"

NETWORK_SITES: list[dict[str, str]] = [
    {
        "host": "copecheck.com",
        "url": "https://copecheck.com/",
        "label": "Main Oracle",
        "theme": "AI displacement denial and elite comfort narratives",
        "role": "Canonical public archive for scored claims and Oracle entries.",
    },
    {
        "host": "codex.copecheck.com",
        "url": "https://codex.copecheck.com/",
        "label": "Codex Cockpit",
        "theme": "Unified submission, routing, scoring and publishing layer",
        "role": "The public prototype for user submissions, queue status and network orchestration.",
    },
    {
        "host": "uk.copecheck.com",
        "url": "https://uk.copecheck.com/",
        "label": "UK Scanner",
        "theme": "UK stagnation, political denial and YouTube scanner outputs",
        "role": "Keeps UK-specific content out of the global feed while giving it a stronger topical home.",
    },
    {
        "host": "layoffs.copecheck.com",
        "url": "https://layoffs.copecheck.com/",
        "label": "Layoffs",
        "theme": "Layoff announcements, workforce reductions and automation cover stories",
        "role": "Turns layoffs into their own archive rather than burying them in the main Oracle.",
    },
    {
        "host": "corporate.copecheck.com",
        "url": "https://corporate.copecheck.com/",
        "label": "Corporate Cope",
        "theme": "Company earnings, SEC filings, investor releases and consultancy reports",
[redacted secret-like line]
    },
    {
        "host": "policy.copecheck.com",
        "url": "https://policy.copecheck.com/",
        "label": "Policy",
        "theme": "Think tanks, policy papers and institutional narratives",
        "role": "Tracks official-looking optimism and policy avoidance with a separate research surface.",
    },
    {
        "host": "data.copecheck.com",
        "url": "https://data.copecheck.com/",
        "label": "Data",
        "theme": "Charts, labour data and repeatable indicators",
        "role": "Provides the quantitative backbone behind the rest of the network.",
    },
    {
        "host": "analytics.copecheck.com",
        "url": "https://analytics.copecheck.com/",
        "label": "Analytics",
        "theme": "Network telemetry and operational reporting",
        "role": "Tracks the operating layer and gives the project a public proof surface for progress.",
    },
    {
        "host": "careers.copecheck.com",
        "url": "https://careers.copecheck.com/",
        "label": "Careers",
        "theme": "Career advice, employability myths and labour market reality",
        "role": "Separates worker-facing advice from the political and corporate claim archive.",
    },
    {
        "host": "countries.copecheck.com",
        "url": "https://countries.copecheck.com/",
        "label": "Countries",
        "theme": "Country-level exposure, resilience and denial patterns",
        "role": "Lets geographic pages expand without cluttering one giant sitemap.",
    },
    {
        "host": "eu.copecheck.com",
        "url": "https://eu.copecheck.com/",
        "label": "EU",
        "theme": "European labour markets, regulation and institutional rhetoric",
        "role": "Gives EU content its own topical boundary and crawlable index.",
    },
    {
        "host": "cities.copecheck.com",
        "url": "https://cities.copecheck.com/",
        "label": "Cities",
        "theme": "Local exposure, rents, wages and regional fragility",
        "role": "Supports city-level programmatic pages without swamping the main domain.",
    },
    {
        "host": "funding.copecheck.com",
        "url": "https://funding.copecheck.com/",
        "label": "Funding",
        "theme": "Capital, grants, subsidies and who actually captures upside",
        "role": "Keeps funding and incentive analysis linkable as a separate research lane.",
    },
    {
        "host": "quiz.copecheck.com",
        "url": "https://quiz.copecheck.com/",
        "label": "Quiz",
        "theme": "Interactive explainers and public tests",
        "role": "A low-friction entry point for people who will not start with a long archive.",
    },
]

HOST_ALIASES = {
    "copecheck.com": "www.copecheck.com",
}

AUTO_SITE_META = {
    "www.copecheck.com": {
        "label": "Main Oracle",
        "theme": "AI displacement denial and elite comfort narratives",
        "role": "Canonical public archive for scored claims and Oracle entries.",
    },
    "labs.copecheck.com": {
        "label": "Labs",
        "theme": "Experiments, prototypes and new CopeCheck surfaces",
        "role": "A staging lane for new public experiments before they graduate into a focused archive.",
    },
}

SEO_PAGES: list[dict[str, str]] = [
    {
        "path": "/",
        "title": "CopeCheck SEO Lab",
        "description": "Live public dashboard for the CopeCheck subdomain network, crawl status and SEO rationale.",
    },
    {
        "path": "/rationale/",
        "title": "Why CopeCheck Uses Subdomains",
        "description": "The topical rationale behind the CopeCheck subdomain network.",
    },
    {
        "path": "/subdomains/",
        "title": "CopeCheck Network Index",
        "description": "A live crawlable index of the CopeCheck subdomains and their sitemap health.",
    },
    {
        "path": "/quality-system/",
        "title": "Programmatic Content Quality System",
        "description": "How CopeCheck keeps source-backed programmatic pages away from scaled-content slop.",
    },
    {
        "path": "/search-progress/",
        "title": "Public Search Progress",
        "description": "The public build log for Search Console, Bing Webmaster Tools and crawl visibility.",
    },
    {
        "path": "/search-console-api/",
        "title": "Search Console API Control Plane",
        "description": "How CopeCheck uses the Search Console API to submit sitemaps, inspect URLs and publish search progress without exposing credentials.",
    },
    {
        "path": "/tool/",
        "title": "Free SEO and AI Crawl Checker",
        "description": "Run a live SEO audit with indexability, organic traffic outlook, Google AI Search readiness, AI crawler access and competitor SERP checks.",
    },
    {
        "path": "/google-ai-search/",
        "title": "Google AI Search Readiness",
        "description": "How the SEO checker maps Google's official AI Search guidance into eligibility, snippet, non-commodity content, query fan-out and agentic UX checks.",
    },
    {
        "path": "/updates/",
        "title": "CopeCheck SEO Updates",
        "description": "A public changelog for CopeCheck SEO work, crawler fixes, sitemap changes, feedback improvements and search visibility experiments.",
    },
]

SOURCE_LINKS = [
    {
        "label": "Google Search: optimizing for generative AI features",
        "url": GOOGLE_AI_GUIDE_URL,
    },
    {
        "label": "Chrome Lighthouse: agentic browsing scoring",
        "url": LIGHTHOUSE_AGENTIC_SCORING_URL,
    },
    {
        "label": "Chrome Lighthouse: llms.txt audit",
        "url": LIGHTHOUSE_LLMS_TXT_URL,
    },
    {
        "label": "Chrome Lighthouse: registered WebMCP tools",
        "url": LIGHTHOUSE_WEBMCP_TOOLS_URL,
    },
    {
        "label": "Google Search: AI-generated content guidance",
        "url": "https://developers.google.com/search/docs/fundamentals/using-gen-ai-content",
    },
    {
        "label": "Google Search spam policies: scaled content abuse",
        "url": "https://developers.google.com/search/docs/essentials/spam-policies#scaled-content",
    },
    {
        "label": "Google Search sitemap guidance",
        "url": "https://developers.google.com/search/docs/crawling-indexing/sitemaps/overview",
    },
    {
        "label": "Bing Webmaster: sitemaps and AI-powered search discovery",
        "url": "https://blogs.bing.com/webmaster/July-2025/[redacted]",
    },
]

SEARCH_CONSOLE_API_LINKS = [
    {
        "label": "Search Console API overview",
        "url": "https://developers.google.com/webmaster-tools/about",
    },
    {
        "label": "Search Console API reference",
        "url": "https://developers.google.com/webmaster-tools/v1/api_reference_index",
    },
    {
        "label": "Sites API add",
        "url": "https://developers.google.com/webmaster-tools/v1/sites/add",
    },
    {
        "label": "Sitemaps API submit",
        "url": "https://developers.google.com/webmaster-tools/v1/sitemaps/submit",
    },
    {
        "label": "Search Analytics API",
        "url": "https://developers.google.com/webmaster-tools/v1/searchanalytics/query",
    },
    {
        "label": "URL Inspection API",
        "url": "https://developers.google.com/search/blog/2022/01/url-inspection-api",
    },
    {
        "label": "Indexing API scope",
        "url": "https://developers.google.com/search/apis/indexing-api/v3/using-api",
    },
]

SEO_UPDATES: list[dict[str, str]] = [
    {
        "date": "2026-05-29",
        "title": "Agentic browsing checks added",
        "summary": "The audit tool now maps Chrome Lighthouse's experimental agentic browsing guidance into llms.txt fetch behaviour, static WebMCP hints, accessibility-tree basics and a Lighthouse follow-up link.",
        "url": "/tool/",
    },
    {
        "date": "2026-05-15",
        "title": "Organic traffic outlook score added",
        "summary": "The audit tool now includes a conservative open-web traffic forecast so clean SEO does not get confused with likely traffic growth.",
        "url": "/tool/",
    },
    {
        "date": "2026-05-15",
        "title": "Google AI Search readiness checks added",
        "summary": "The audit tool now tests Google AI Search eligibility, snippet controls, non-commodity content signals, query fan-out coverage and browser-agent readability using Google's latest Search Central guidance.",
        "url": "/google-ai-search/",
    },
    {
        "date": "2026-05-14",
        "title": "Cloudflare edge robots checks added",
        "summary": "The SEO checker now reads the public Cloudflare edge robots response, detects managed robots/content-signal policy and flags hidden AI crawler block risk.",
        "url": "/tool/",
    },
    {
        "date": "2026-05-14",
        "title": "Feedback popup wired into the SEO tool",
        "summary": "Every SEO Lab page now has a feedback popup that stores the page, feedback type and latest audit context for later incorporation.",
        "url": "/tool/",
    },
    {
        "date": "2026-05-14",
        "title": "Shareable audits and competitor re-runs",
        "summary": "Audit results now produce a share URL, and competitor results link straight back into the checker so the same query can be run on another domain.",
        "url": "/tool/",
    },
    {
        "date": "2026-05-14",
        "title": "Search Console trend surface added",
        "summary": "Clicks, impressions, CTR and page/query movement are visible on the public progress dashboard from the sanitized Search Console snapshot.",
        "url": "/search-progress/",
    },
    {
        "date": "2026-05-14",
        "title": "Subdomain registry sync documented",
        "summary": "The SEO Lab records how new CopeCheck tunnel hosts are pulled into the public network index and sitemap dashboard automatically.",
        "url": "/subdomains/",
    },
]


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def load_env_file(path: Path) -> None:
    if not path.exists():
        return
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))


def load_runtime_env() -> None:
    load_env_file(BASE / ".env")
    shared = os.getenv("COPECHECK_SHARED_ENV")
    if shared:
        load_env_file(Path(shared))


def escape(value: Any) -> str:
    if value is None:
        return ""
    return html.escape(str(value), quote=True)


def clamp_words(value: Any, limit: int = 34) -> str:
    text = re.sub(r"\s+", " ", str(value or "")).strip()
    if not text:
        return ""
    words = text.split(" ")
    if len(words) <= limit:
        return text
    return " ".join(words[:limit]).rstrip(".,;:") + "..."


def canonical_host(host: Any) -> str:
    raw = str(host or "").strip().lower().removeprefix("https://").removeprefix("http://")
    raw = raw.split("/", 1)[0]
    return HOST_ALIASES.get(raw, raw)


def canonical_site(site: dict[str, Any]) -> dict[str, str]:
    host = canonical_host(site.get("host") or site.get("url"))
    url = str(site.get("url") or f"https://{host}/").strip()
    if not url.startswith(("http://", "https://")):
        url = f"https://{host}/"
    parsed = urlparse(url)
    if parsed.netloc:
        host = canonical_host(parsed.netloc)
    url = f"https://{host}/"
    subdomain = host.removesuffix(".copecheck.com").removeprefix("www")
    pretty = "Main" if host == "www.copecheck.com" else subdomain.replace("-", " ").title()
    inferred = {
        "label": pretty,
        "theme": "Auto-discovered CopeCheck surface",
        "role": "Discovered from the live tunnel registry and checked by the SEO lab.",
    }
    inferred.update(AUTO_SITE_META.get(host, {}))
    return {
        "host": host,
        "url": url,
        "label": str(site.get("label") or inferred["label"]),
        "theme": str(site.get("theme") or inferred["theme"]),
        "role": str(site.get("role") or inferred["role"]),
        "source": str(site.get("source") or "curated"),
        "service": str(site.get("service") or ""),
    }


def load_site_registry() -> dict[str, Any]:
    if not SITE_REGISTRY_FILE.exists():
        return {"generated_at": None, "sites": []}
    try:
        data = json.loads(SITE_REGISTRY_FILE.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {"generated_at": None, "sites": []}
    return data if isinstance(data, dict) else {"generated_at": None, "sites": []}


def load_network_sites() -> tuple[list[dict[str, str]], dict[str, Any]]:
    registry = load_site_registry()
    merged: dict[str, dict[str, str]] = {}
    for site in NETWORK_SITES:
        item = canonical_site(site)
        merged[item["host"]] = item
    for site in registry.get("sites") or []:
        if not isinstance(site, dict):
            continue
        item = canonical_site(site)
        existing = merged.get(item["host"], {})
        merged[item["host"]] = {**item, **existing, "source": item.get("source") or existing.get("source", "registry")}
        if item.get("service"):
            merged[item["host"]]["service"] = item["service"]

    preferred = [canonical_site(site)["host"] for site in NETWORK_SITES]
    order = {host: index for index, host in enumerate(dict.fromkeys(preferred))}
    sites = sorted(
        merged.values(),
        key=lambda item: (order.get(item["host"], 10_000), item["host"]),
    )
    return sites, registry


def request_url(url: str, method: str = "GET", timeout: float = FETCH_TIMEOUT) -> dict[str, Any]:
    headers = {
        "User-Agent": "CopeCheckSEO/1.0 (+https://seo.copecheck.com/)",
        "Accept": "text/html,application/xml,application/json;q=0.9,*/*;q=0.8",
    }
    req = Request(url, method=method, headers=headers)
    started = time.perf_counter()
    try:
        with urlopen(req, timeout=timeout) as response:
            body = b""
            if method != "HEAD":
                body = response.read(600_000)
            return {
                "ok": 200 <= response.status < 400,
                "status": response.status,
                "url": response.url,
                "content_type": response.headers.get("content-type", ""),
                "headers": dict(response.headers),
                "body": body,
                "elapsed_ms": int((time.perf_counter() - started) * 1000),
                "error": "",
            }
    except HTTPError as exc:
        body = b""
        try:
            body = exc.read(120_000) if method != "HEAD" else b""
        except Exception:
            body = b""
        return {
            "ok": False,
            "status": exc.code,
            "url": url,
            "content_type": exc.headers.get("content-type", "") if exc.headers else "",
            "headers": dict(exc.headers or {}),
            "body": body,
            "elapsed_ms": int((time.perf_counter() - started) * 1000),
            "error": str(exc),
        }
    except (URLError, TimeoutError, OSError) as exc:
        return {
            "ok": False,
            "status": 0,
            "url": url,
            "content_type": "",
            "headers": {},
            "body": b"",
            "elapsed_ms": int((time.perf_counter() - started) * 1000),
            "error": str(exc),
        }


def header_get(headers: dict[str, Any] | None, name: str) -> str:
    needle = name.lower()
    for key, value in (headers or {}).items():
        if str(key).lower() == needle:
            return str(value)
    return ""


def served_by_cloudflare(response: dict[str, Any]) -> bool:
    headers = response.get("headers") if isinstance(response.get("headers"), dict) else {}
    server = header_get(headers, "server").lower()
    return (
        "cloudflare" in server
        or bool(header_get(headers, "cf-ray"))
        or bool(header_get(headers, "cf-cache-status"))
        or bool(header_get(headers, "cf-mitigated"))
    )


def count_sitemap_urls(body: bytes) -> tuple[int, str | None]:
    if not body:
        return 0, None
    text = body.decode("utf-8", errors="ignore")
    loc_count = len(re.findall(r"<loc>\s*https?://", text, flags=re.I))
    lastmod_match = re.search(r"<lastmod>\s*([^<]+)\s*</lastmod>", text, flags=re.I)
    return loc_count, lastmod_match.group(1).strip() if lastmod_match else None


class SEOHTMLParser(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.title = ""
        self.lang = ""
        self.metas: list[dict[str, str]] = []
        self.links: list[dict[str, str]] = []
        self.headings: dict[str, list[str]] = {"h1": [], "h2": [], "h3": []}
        self.images: list[dict[str, str]] = []
        self.anchors: list[dict[str, str]] = []
        self.videos: list[dict[str, str]] = []
        self.iframes: list[dict[str, str]] = []
        self.jsonld_scripts: list[str] = []
        self.body_chunks: list[str] = []
        self.tag_counts: dict[str, int] = {}
        self.data_nosnippet_count = 0
        self.form_count = 0
        self.input_count = 0
        self.label_count = 0
        self.button_count = 0
        self.webmcp_tools: list[dict[str, str]] = []
        self.inline_scripts: list[str] = []
        self._capture_tag = ""
        self._capture_kind = ""
        self._capture_buffer: list[str] = []
        self._skip_depth = 0

    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
        tag = tag.lower()
        attr_map = {str(key).lower(): str(value or "") for key, value in attrs}
        self.tag_counts[tag] = self.tag_counts.get(tag, 0) + 1
        if "data-nosnippet" in attr_map:
            self.data_nosnippet_count += 1
        if tag == "html":
            self.lang = attr_map.get("lang", "")
        if tag == "meta":
            self.metas.append(attr_map)
        elif tag == "link":
            self.links.append(attr_map)
        elif tag == "img":
            self.images.append(attr_map)
        elif tag == "a":
            self.anchors.append(attr_map)
        elif tag == "video":
            self.videos.append(attr_map)
        elif tag == "iframe":
            self.iframes.append(attr_map)
        elif tag == "form":
            self.form_count += 1
            tool_name = attr_map.get("toolname") or attr_map.get("data-toolname")
            tool_description = attr_map.get("tooldescription") or attr_map.get("data-tooldescription")
            if tool_name or tool_description:
                self.webmcp_tools.append({
                    "name": tool_name.strip() or "unnamed_form_tool",
                    "description": tool_description.strip(),
                    "source": "declarative_form",
                })
        elif tag in {"input", "select", "textarea"}:
            self.input_count += 1
        elif tag == "label":
            self.label_count += 1
        elif tag == "button":
            self.button_count += 1

        if tag in {"title", "h1", "h2", "h3"}:
            self._capture_tag = tag
            self._capture_kind = "text"
            self._capture_buffer = []
            return

        if tag == "script":
            if "ld+json" in attr_map.get("type", "").lower():
                self._capture_tag = tag
                self._capture_kind = "jsonld"
                self._capture_buffer = []
            elif not attr_map.get("src"):
                self._capture_tag = tag
                self._capture_kind = "script"
                self._capture_buffer = []
            else:
                self._skip_depth += 1
            return

        if tag in {"style", "noscript", "template"}:
            self._skip_depth += 1

    def handle_endtag(self, tag: str) -> None:
        tag = tag.lower()
        if self._capture_tag == tag:
            text = re.sub(r"\s+", " ", " ".join(self._capture_buffer)).strip()
            if self._capture_kind == "jsonld" and text:
                self.jsonld_scripts.append(text)
            elif self._capture_kind == "script" and text:
                self.inline_scripts.append(text[:8000])
            elif self._capture_kind == "text" and text:
                if tag == "title" and not self.title:
                    self.title = text
                elif tag in self.headings:
                    self.headings[tag].append(text)
            self._capture_tag = ""
            self._capture_kind = ""
            self._capture_buffer = []
            return
        if tag in {"script", "style", "noscript", "template"} and self._skip_depth:
            self._skip_depth -= 1

    def handle_data(self, data: str) -> None:
        text = data.strip()
        if not text:
            return
        if self._capture_tag:
            self._capture_buffer.append(text)
            return
        if not self._skip_depth:
            self.body_chunks.append(text)


def decode_body(response: dict[str, Any]) -> str:
    body = response.get("body") or b""
    if not isinstance(body, bytes):
        return ""
    content_type = str(response.get("content_type") or "")
    charset_match = re.search(r"charset=([\w.-]+)", content_type, flags=re.I)
    charset = charset_match.group(1) if charset_match else "utf-8"
    try:
        return body.decode(charset, errors="ignore")
    except LookupError:
        return body.decode("utf-8", errors="ignore")


def parse_html_document(response: dict[str, Any]) -> SEOHTMLParser:
    parser = SEOHTMLParser()
    text = decode_body(response)
    if text:
        try:
            parser.feed(text)
        except Exception:
            pass
    return parser


def first_meta(parser: SEOHTMLParser, name: str = "", prop: str = "") -> str:
    target_name = name.lower()
    target_prop = prop.lower()
    for meta in parser.metas:
        if target_name and meta.get("name", "").lower() == target_name:
            return meta.get("content", "").strip()
        if target_prop and meta.get("property", "").lower() == target_prop:
            return meta.get("content", "").strip()
    return ""


def link_rel(parser: SEOHTMLParser, rel_name: str) -> str:
    needle = rel_name.lower()
    for link in parser.links:
        rel = link.get("rel", "").lower()
        parts = {part.strip() for part in re.split(r"\s+", rel) if part.strip()}
        if needle in parts:
            return link.get("href", "").strip()
    return ""


def extract_schema_types(parser: SEOHTMLParser) -> list[str]:
    found: set[str] = set()

    def walk(value: Any) -> None:
        if isinstance(value, dict):
            raw_type = value.get("@type") or value.get("type")
            if isinstance(raw_type, str):
                found.add(raw_type)
            elif isinstance(raw_type, list):
                for item in raw_type:
                    if isinstance(item, str):
                        found.add(item)
            graph = value.get("@graph")
            if isinstance(graph, list):
                for item in graph:
                    walk(item)
            for key in ("mainEntity", "about", "itemListElement"):
                item = value.get(key)
                if isinstance(item, (dict, list)):
                    walk(item)
        elif isinstance(value, list):
            for item in value:
                walk(item)

    for script in parser.jsonld_scripts[:10]:
        try:
            walk(json.loads(script))
        except json.JSONDecodeError:
            continue
    return sorted(found)


def public_host_allowed(host: str) -> bool:
    cleaned = host.strip().strip("[]").lower()
    if not cleaned or cleaned in {"localhost", "0.0.0.0"} or cleaned.endswith(".local"):
        return False
    try:
        addresses = [ipaddress.ip_address(cleaned)]
    except ValueError:
        try:
            infos = socket.getaddrinfo(cleaned, None, type=socket.SOCK_STREAM)
            addresses = [ipaddress.ip_address(info[4][0]) for info in infos]
        except OSError:
            return False
    return bool(addresses) and all(address.is_global for address in addresses)


def normalise_audit_url(raw_url: str) -> str:
    value = str(raw_url or "").strip()
    if not value:
        raise ValueError("Enter a URL to audit.")
    if not re.match(r"^https?://", value, flags=re.I):
        value = f"https://{value}"
    parsed = urlparse(value)
    if parsed.scheme.lower() not in {"http", "https"}:
        raise ValueError("Only http and https URLs can be audited.")
    if not parsed.hostname:
        raise ValueError("That URL does not include a valid host.")
    try:
        host = parsed.hostname.encode("idna").decode("ascii")
    except UnicodeError as exc:
        raise ValueError("That host name is not valid.") from exc
    if not public_host_allowed(host):
        raise ValueError("That URL resolves to a private or non-public address.")
    netloc = host if parsed.port is None else f"{host}:{parsed.port}"
    return parsed._replace(scheme=parsed.scheme.lower(), netloc=netloc, path=parsed.path or "/", fragment="").geturl()


def robots_groups(body: str) -> list[tuple[list[str], list[tuple[str, str]]]]:
    groups: list[tuple[list[str], list[tuple[str, str]]]] = []
    agents: list[str] = []
    rules: list[tuple[str, str]] = []
    for raw_line in body.splitlines() + [""]:
        line = raw_line.split("#", 1)[0].strip()
        if not line:
            if agents or rules:
                groups.append((agents, rules))
            agents = []
            rules = []
            continue
        if ":" not in line:
            continue
        field, value = line.split(":", 1)
        field = field.strip().lower()
        value = value.strip()
        if field == "user-agent":
            if rules:
                groups.append((agents, rules))
                agents = []
                rules = []
            agents.append(value.lower())
        elif field in {"allow", "disallow"}:
            rules.append((field, value))
    return groups


def robots_pattern_matches(pattern: str, path: str) -> bool:
    if pattern == "":
        return False
    escaped = re.escape(pattern).replace(r"\*", ".*")
    if escaped.endswith(r"\$"):
        regex = "^" + escaped[:-2] + "$"
    else:
        regex = "^" + escaped
    return re.match(regex, path) is not None


def robots_allows(body: str, user_agent: str, path: str = "/") -> tuple[bool, str]:
    if not body.strip():
        return True, "No robots policy found."
    groups = robots_groups(body)
    ua = user_agent.lower()
    matched_groups: list[tuple[int, list[tuple[str, str]]]] = []
    for agents, rules in groups:
        match_lengths = [
            1 if agent == "*" else len(agent)
            for agent in agents
            if agent == "*" or agent in ua or ua in agent
        ]
        if match_lengths:
            matched_groups.append((max(match_lengths), rules))
    if not matched_groups:
        return True, f"No rule for {user_agent}."
    best_match = max(length for length, _ in matched_groups)
    applicable = [
        rule
        for length, rules in matched_groups
        if length == best_match
        for rule in rules
    ]
    if not applicable:
        return True, f"No directive for {user_agent}."
    matches: list[tuple[int, str, str]] = []
    for directive, pattern in applicable:
        if robots_pattern_matches(pattern, path):
            matches.append((len(pattern), directive, pattern))
    if not matches:
        return True, f"No matching block for {user_agent}."
    matches.sort(key=lambda item: (item[0], 1 if item[1] == "allow" else 0), reverse=True)
    _, directive, pattern = matches[0]
    if directive == "allow":
        return True, f"Allowed by Allow: {pattern}"
    return False, f"Blocked by Disallow: {pattern}"


def robots_sitemap_directives(body: str) -> list[str]:
    sitemaps: list[str] = []
    for raw_line in body.splitlines():
        line = raw_line.split("#", 1)[0].strip()
        if ":" not in line:
            continue
        field, value = line.split(":", 1)
        if field.strip().lower() == "sitemap":
            sitemap = value.strip()
            if sitemap:
                sitemaps.append(sitemap)
    return sitemaps[:10]


def robots_content_signals(body: str) -> dict[str, str]:
    signals: dict[str, str] = {}
    for raw_line in body.splitlines():
        line = raw_line.split("#", 1)[0].strip()
        if ":" not in line:
            continue
        field, value = line.split(":", 1)
        if field.strip().lower() != "content-signal":
            continue
        for part in value.split(","):
            if "=" not in part:
                continue
            key, signal_value = part.split("=", 1)
            cleaned_key = key.strip().lower()
            if cleaned_key in ROBOTS_CONTENT_SIGNAL_FIELDS:
                signals[cleaned_key] = signal_value.strip().lower()
    return signals


def summarise_content_signals(signals: dict[str, str]) -> str:
    if not signals:
        return "No content-signal policy found."
    return ", ".join(f"{field}={signals.get(field, 'unset')}" for field in ROBOTS_CONTENT_SIGNAL_FIELDS)


def cloudflare_robots_diagnostics(
    response: dict[str, Any],
    body: str,
    ai_policy: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    headers = response.get("headers") if isinstance(response.get("headers"), dict) else {}
    cloudflare_edge = served_by_cloudflare(response)
    body_lower = body.lower()
    markers = [marker for marker in CLOUDFLARE_ROBOTS_MARKERS if marker in body_lower]
    content_signals = robots_content_signals(body)
    blocked_ai = [crawler for crawler, policy in ai_policy.items() if not policy.get("allowed")]
    blocked_discovery = [crawler for crawler in blocked_ai if crawler in AI_DISCOVERY_CRAWLERS]
    search_blocked = content_signals.get("search") in {"no", "0", "false"}
    ai_input_blocked = content_signals.get("ai-input") in {"no", "0", "false"}
    managed_signal = bool(markers or content_signals)
    hidden_ai_block_risk = bool(
        cloudflare_edge
        and (
            (managed_signal and (blocked_discovery or search_blocked or ai_input_blocked))
            or len(blocked_discovery) >= 3
        )
    )
    if not cloudflare_edge:
        detail = "No Cloudflare edge headers detected on the public robots.txt response."
    elif hidden_ai_block_risk:
        detail = f"Cloudflare edge response detected and AI discovery is restricted: {', '.join(blocked_discovery) or summarise_content_signals(content_signals)}."
    elif managed_signal:
        detail = f"Cloudflare edge response detected with managed robots/content signals, but no AI-search block was found. {summarise_content_signals(content_signals)}"
    else:
        detail = "Cloudflare edge response detected; no managed AI-blocking robots policy was found in the public response."
    return {
        "served_by_cloudflare": cloudflare_edge,
        "cf_ray": bool(header_get(headers, "cf-ray")),
        "server": header_get(headers, "server"),
        "managed_markers": markers,
        "content_signals": content_signals,
        "content_signal_summary": summarise_content_signals(content_signals),
        "blocked_ai": blocked_ai,
        "blocked_discovery": blocked_discovery,
        "search_blocked": search_blocked,
        "ai_input_blocked": ai_input_blocked,
        "hidden_ai_block_risk": hidden_ai_block_risk,
        "detail": detail,
    }


def add_audit_check(
    checks: list[dict[str, Any]],
    category: str,
    label: str,
    ok: bool,
    severity: str,
    detail: str,
    recommendation: str,
) -> None:
    checks.append(
        {
            "category": category,
            "label": label,
            "ok": bool(ok),
            "severity": severity,
            "detail": detail,
            "recommendation": recommendation,
        }
    )


def audit_grade(score: int) -> str:
    if score >= 90:
        return "A"
    if score >= 80:
        return "B"
    if score >= 65:
        return "C"
    if score >= 50:
        return "D"
    return "E"


def category_scores(checks: list[dict[str, Any]]) -> dict[str, int]:
    scores = {category: 100 for category in ["technical", "indexability", "content", "ai", "agentic", "google_ai", "serp"]}
    for check in checks:
        if check.get("ok"):
            continue
        category = str(check.get("category") or "technical")
        scores.setdefault(category, 100)
        scores[category] = max(0, scores[category] - AUDIT_SEVERITY_WEIGHT.get(str(check.get("severity")), 4) * 2)
    return scores


def derive_search_query(parser: SEOHTMLParser, host: str) -> str:
    source = parser.title or " ".join(parser.headings.get("h1") or [])
    words = [
        word.lower()
        for word in re.findall(r"[A-Za-z][A-Za-z0-9-]{2,}", source)
        if word.lower() not in STOP_WORDS
    ]
    if words:
        return " ".join(words[:7])
    return host.replace(".", " ")


def snippet_policy(robots_meta: str, x_robots: str, data_nosnippet_count: int) -> dict[str, Any]:
    combined = ",".join(value for value in [robots_meta, x_robots] if value).lower()
    blockers = [
        marker
        for marker in ["nosnippet", "max-snippet:0", "max-snippet: 0"]
        if marker in combined
    ]
    partial = data_nosnippet_count > 0
    if blockers:
        detail = f"Snippet blocker found: {', '.join(dict.fromkeys(blockers))}."
    elif partial:
        detail = f"{data_nosnippet_count} data-nosnippet element(s) found; snippets are generally allowed but some content is withheld."
    else:
        detail = "No noindex, nosnippet or max-snippet:0 directive detected."
    return {
        "allowed": not blockers,
        "partial_data_nosnippet": partial,
        "data_nosnippet_count": data_nosnippet_count,
        "x_robots": x_robots,
        "detail": detail,
    }


def content_quality_profile(
    parser: SEOHTMLParser,
    text: str,
    word_count: int,
    external_links: int,
    schema_types: list[str],
) -> dict[str, Any]:
    title = parser.title or " ".join(parser.headings.get("h1") or [])
    title_lower = title.lower()
    body_lower = f" {text.lower()} "
    commodity_patterns = [
        r"^\s*\d+\s+(tips|ways|things|ideas|reasons|best|top)\b",
        r"\b(ultimate guide|complete guide|everything you need to know|best practices)\b",
        r"\b(how to|what is|beginners guide|beginner's guide)\b",
    ]
    commodity_hits = [pattern for pattern in commodity_patterns if re.search(pattern, title_lower)]
    signal_terms = {
        "first-hand": [" first-hand ", " firsthand ", " our ", " we ", " tested ", " built ", " measured "],
        "evidence": [" source ", " evidence ", " dataset ", " benchmark ", " citation ", " research ", " report "],
        "specificity": [" case study ", " example ", " pricing ", " date ", " updated ", " methodology ", " limitation "],
        "opinion": [" thesis ", " verdict ", " rationale ", " analysis ", " critique ", " point of view "],
    }
    matched_signals = [
        label
        for label, needles in signal_terms.items()
        if any(needle in body_lower for needle in needles)
    ]
    structure_points = 0
    if len(parser.headings.get("h2", [])) >= 2:
        structure_points += 18
    if parser.tag_counts.get("p", 0) >= 4:
        structure_points += 12
    if external_links >= 1:
        structure_points += 14
    if schema_types:
        structure_points += 8
    score = min(100, structure_points + min(30, word_count // 20) + len(matched_signals) * 10)
    if commodity_hits:
        score = max(0, score - 20)
    return {
        "score": score,
        "commodity_risk": "high" if commodity_hits and score < 60 else "medium" if commodity_hits else "low",
        "commodity_hits": commodity_hits,
        "matched_signals": matched_signals,
        "paragraph_count": parser.tag_counts.get("p", 0),
        "h2_count": len(parser.headings.get("h2", [])),
        "detail": (
            f"Quality profile {score}/100 with {len(matched_signals)} unique-value signal(s), "
            f"{parser.tag_counts.get('p', 0)} paragraph(s) and {len(parser.headings.get('h2', []))} H2 heading(s)."
        ),
    }


def build_query_fanout(search_query: str, market: str) -> list[dict[str, str]]:
    base = re.sub(r"\s+", " ", search_query or "").strip()
    if not base:
        base = "target topic"
    market_suffix = market.strip() or "target market"
    templates = [
        ("definition", f"what is {base}", "Make the page answer the plain-language definition without burying the answer."),
        ("evidence", f"{base} evidence examples", "Add concrete examples, source links, screenshots, data or named cases."),
        ("comparison", f"{base} alternatives comparison", "Explain how the page's point of view differs from obvious alternatives."),
        ("local", f"{base} {market_suffix}", "Cover the market-specific angle if the page targets a location or jurisdiction."),
        ("cost", f"{base} pricing cost risk", "Handle pricing, risk, effort or commercial impact if that affects the decision."),
        ("freshness", f"latest {base} updates", "Show what changed recently and when the page was last reviewed."),
    ]
    return [
        {"intent": intent, "query": query, "content_move": move}
        for intent, query, move in templates
    ]


def build_agentic_profile(parser: SEOHTMLParser, llms_status: int | None, llms_ok: bool) -> dict[str, Any]:
    landmarks = {
        "main": parser.tag_counts.get("main", 0),
        "article": parser.tag_counts.get("article", 0),
        "nav": parser.tag_counts.get("nav", 0),
        "header": parser.tag_counts.get("header", 0),
        "footer": parser.tag_counts.get("footer", 0),
        "section": parser.tag_counts.get("section", 0),
    }
    has_landmark = bool(landmarks["main"] or landmarks["article"])
    form_readable = parser.input_count == 0 or parser.label_count >= max(1, min(parser.input_count, 3))
    imperative_webmcp = any(
        "navigator.modelcontext.registertool" in script.lower()
        or "navigator.modelcontext.registertool" in script.replace(" ", "").lower()
        for script in parser.inline_scripts
    )
    webmcp_tools = list(parser.webmcp_tools)
    if imperative_webmcp:
        webmcp_tools.append({
            "name": "imperative_webmcp_registration",
            "description": "Inline script references navigator.modelContext.registerTool.",
            "source": "imperative_script",
        })
    if webmcp_tools:
        webmcp_status = "present"
        webmcp_detail = f"{len(webmcp_tools)} static WebMCP registration hint(s) detected."
    elif parser.form_count or parser.button_count:
        webmcp_status = "opportunity"
        webmcp_detail = "No static WebMCP tools detected; forms/actions could expose tool names and descriptions for agents."
    else:
        webmcp_status = "not_applicable"
        webmcp_detail = "No obvious action surface detected for WebMCP tool registration."
    llms_fetch_ok = bool(llms_ok) or llms_status == 404
    if llms_ok:
        llms_detail = "llms.txt is available at the domain root."
        llms_status_label = "present"
    elif llms_status == 404:
        llms_detail = "llms.txt returned 404; Lighthouse currently treats that as optional/N/A, not a hard failure."
        llms_status_label = "optional_missing"
    else:
        llms_detail = f"llms.txt returned HTTP {llms_status or 'offline'}; fix server errors before relying on it for agents."
        llms_status_label = "error"
    status = "ready" if has_landmark and form_readable and llms_fetch_ok else "needs work"
    return {
        "status": status,
        "landmarks": landmarks,
        "forms": parser.form_count,
        "inputs": parser.input_count,
        "labels": parser.label_count,
        "buttons": parser.button_count,
        "webmcp_status": webmcp_status,
        "webmcp_tools": webmcp_tools,
        "webmcp_detail": webmcp_detail,
        "llms_status": llms_status,
        "llms_status_label": llms_status_label,
        "llms_fetch_ok": llms_fetch_ok,
        "llms_detail": llms_detail,
        "lighthouse_source": LIGHTHOUSE_AGENTIC_SCORING_URL,
        "detail": (
            f"{sum(1 for count in landmarks.values() if count)} semantic landmark type(s), "
            f"{parser.form_count} form(s), {parser.input_count} input(s), {parser.label_count} label(s), "
            f"WebMCP {webmcp_status}, llms.txt {llms_status_label}."
        ),
    }


def build_google_ai_readiness(
    score: int,
    search_query: str,
    market: str,
    eligible: bool,
    snippet: dict[str, Any],
    content_profile: dict[str, Any],
    agentic_profile: dict[str, Any],
    images_total: int,
    videos_total: int,
    schema_types: list[str],
) -> dict[str, Any]:
    if not eligible:
        status = "blocked"
    elif score >= 82:
        status = "ready"
    elif score >= 62:
        status = "warm"
    else:
        status = "thin"
    media_detail = (
        f"{images_total} image(s) and {videos_total} video element(s) detected."
        if images_total or videos_total
        else "No page media detected; add useful images or video where they genuinely help the visitor."
    )
    structured_data_detail = (
        f"Schema detected: {', '.join(schema_types)}."
        if schema_types
        else "Structured data is not required for Google AI Search, but relevant schema can still help rich results."
    )
    return {
        "score": score,
        "status": status,
        "source": GOOGLE_AI_GUIDE_URL,
        "eligibility": {
            "eligible": eligible,
            "snippet_allowed": snippet["allowed"],
            "detail": snippet["detail"],
        },
        "content_quality": content_profile,
        "agentic": agentic_profile,
        "fanout_queries": build_query_fanout(search_query, market),
        "tools": [
            {
                "name": "Google AI eligibility inspector",
                "status": "ready" if eligible else "blocked",
                "detail": "Checks HTTP, Googlebot access, noindex and snippet eligibility. Google AI features draw from pages that can appear in normal Search with snippets.",
            },
            {
                "name": "Query fan-out planner",
                "status": "ready",
                "detail": "Turns the target query into related intents to cover inside the page, not as thin doorway pages.",
            },
            {
                "name": "Non-commodity content detector",
                "status": content_profile["commodity_risk"],
                "detail": content_profile["detail"],
            },
            {
                "name": "Browser-agent UX check",
                "status": agentic_profile["status"],
                "detail": agentic_profile["detail"],
            },
            {
                "name": "Lighthouse Agentic Browsing follow-up",
                "status": "external",
                "detail": "Chrome Lighthouse now exposes deterministic agentic browsing checks for WebMCP, accessibility-tree quality, layout stability and llms.txt fetch behaviour.",
                "url": LIGHTHOUSE_AGENTIC_SCORING_URL,
            },
            {
                "name": "WebMCP static hints",
                "status": agentic_profile["webmcp_status"],
                "detail": agentic_profile["webmcp_detail"],
                "url": LIGHTHOUSE_WEBMCP_TOOLS_URL,
            },
            {
                "name": "llms.txt agent summary",
                "status": agentic_profile["llms_status_label"],
                "detail": agentic_profile["llms_detail"],
                "url": LIGHTHOUSE_LLMS_TXT_URL,
            },
            {
                "name": "Media and rich result helper",
                "status": "present" if images_total or videos_total or schema_types else "opportunity",
                "detail": f"{media_detail} {structured_data_detail}",
            },
            {
                "name": "PageSpeed Insights follow-up",
                "status": "external",
                "detail": "Run Core Web Vitals separately after content and crawl blockers are fixed.",
            },
        ],
        "mythbusters": [
            "Do not create llms.txt or special AI markup because you think Google AI Search requires it. It does not.",
            "Do treat llms.txt as useful optional infrastructure for browser agents and non-Google LLM tools where it helps them understand the site faster.",
            "Do not split useful pages into tiny chunks just for AI systems. Make the page satisfy the visitor.",
            "Do not build separate pages for every fan-out query unless each page has a real user purpose.",
            "Do not chase fake mentions. Google says core quality and spam systems still matter.",
            "Do not over-focus on schema. Use it where it helps rich results, not as an AI Search hack.",
        ],
    }


def build_organic_traffic_outlook(
    audit_url: str,
    host: str,
    search_query: str,
    market: str,
    parser: SEOHTMLParser,
    text: str,
    word_count: int,
    external_links: int,
    competitors: list[dict[str, str]],
    schema_types: list[str],
    page_ok: bool,
    page_indexable: bool,
    googlebot_allowed: bool,
    snippet_allowed: bool,
    google_ai_score: int,
    content_profile: dict[str, Any],
) -> dict[str, Any]:
    query = re.sub(r"\s+", " ", search_query or "").strip().lower()
    title = (parser.title or " ".join(parser.headings.get("h1", []))).lower()
    combined = f" {query} {title} {text.lower()} "
    path = urlparse(audit_url).path.lower()
    host_parts = [part for part in host.lower().removeprefix("www.").split(".") if part]
    generic_subdomains = {
        "www",
        "seo",
        "blog",
        "docs",
        "app",
        "shop",
        "store",
        "support",
        "help",
        "news",
        "uk",
        "eu",
        "data",
        "analytics",
        "careers",
        "cities",
        "countries",
        "policy",
        "funding",
        "quiz",
        "thesis",
        "capabilities",
    }
    brand_candidates = {host_parts[-2]} if len(host_parts) >= 2 else set(host_parts)
    if len(host_parts) > 2 and host_parts[0] not in generic_subdomains:
        brand_candidates.add(host_parts[0])
    schema_set = {schema.lower() for schema in schema_types}
    commercial_terms = {
        "buy",
        "price",
        "pricing",
        "cost",
        "quote",
        "book",
        "hire",
        "agency",
        "consultant",
        "service",
        "services",
        "software",
        "platform",
        "tool",
        "near me",
        "shop",
        "best",
    }
    informational_terms = {
        "what is",
        "how to",
        "guide",
        "tips",
        "news",
        "blog",
        "examples",
        "why",
        "explained",
        "definition",
    }
    local_terms = {
        "near me",
        "london",
        "manchester",
        "birmingham",
        "dublin",
        "ireland",
        "uk",
        "united kingdom",
        "local",
    }
    original_terms = {
        "data",
        "dataset",
        "calculator",
        "checker",
        "tool",
        "benchmark",
        "research",
        "methodology",
        "case study",
        "thesis",
        "oracle",
        "score",
        "live",
    }
    is_brand = any(
        candidate
        and len(candidate) >= 4
        and candidate not in generic_subdomains
        and re.search(rf"\b{re.escape(candidate)}\b", query.replace("-", " "))
        for candidate in brand_candidates
    )
    has_commercial = any(f" {term} " in combined for term in commercial_terms)
    has_informational = any(f" {term} " in combined for term in informational_terms)
    has_local = any(f" {term} " in combined for term in local_terms)
    has_original = any(f" {term} " in combined for term in original_terms)
    has_product_schema = bool(schema_set & {"product", "offer", "aggregateoffer"})
    has_local_schema = bool(schema_set & {"localbusiness", "place"})
    has_content_schema = bool(schema_set & {"article", "blogposting", "newsarticle", "creativework"})
    has_tool_schema = bool(schema_set & {"softwareapplication", "dataset", "webapplication"})

    if not page_ok or not page_indexable or not googlebot_allowed or not snippet_allowed:
        return {
            "score": 0,
            "band": "blocked",
            "page_type": "not eligible",
            "summary": "Organic traffic outlook is effectively zero because the page is not fully eligible for normal Google Search discovery and snippets.",
            "expected": "No reliable organic traffic until crawl, index or snippet blockers are fixed.",
            "risks": ["The page is not fully crawlable, indexable or snippet-eligible."],
            "levers": ["Fix indexability before caring about demand, content or links."],
            "assumptions": ["This is a conservative open-web forecast, not a keyword-volume estimate."],
        }

    if is_brand:
        page_type = "brand or navigational"
        score = 44
    elif has_local or has_local_schema:
        page_type = "local or service"
        score = 32
    elif has_tool_schema or has_original:
        page_type = "tool, data or original research"
        score = 34
    elif has_product_schema or has_commercial:
        page_type = "commercial or ecommerce"
        score = 18
    elif has_content_schema or has_informational or "/blog" in path or "/news" in path:
        page_type = "content or informational"
        score = 12
    else:
        page_type = "general niche page"
        score = 22

    risks: list[str] = []
    levers: list[str] = [
        "Treat organic search as proof, capture and credibility rather than the whole acquisition strategy.",
        "Build direct, referral, email and branded demand so the page is not dependent on open-web discovery.",
    ]

    ads_risk = "low"
    if has_product_schema or has_commercial:
        ads_risk = "high"
        score -= 12
        risks.append("Commercial SERPs are ad-heavy and comparison-heavy, so even good organic rankings may sit below paid results and aggregators.")
    elif any(term in combined for term in ("price", "cost", "quote", "near me", "book")):
        ads_risk = "medium"
        score -= 7
        risks.append("The query has transactional signals, so paid results can compress organic clicks.")

    ai_answer_risk = "low"
    if has_informational and not (has_original or has_tool_schema):
        ai_answer_risk = "high"
        score -= 12
        risks.append("Informational content is exposed to zero-click answers, featured snippets and AI summaries.")
    elif has_informational:
        ai_answer_risk = "medium"
        score -= 6
        risks.append("Some query demand may be answered on the results page before a visitor reaches the site.")

    if not is_brand:
        score -= 8
        risks.append("Small or non-branded pages have weak default demand unless another channel creates awareness.")
    if competitors and len(competitors) >= 7:
        score -= 5
        risks.append(f"The live SERP returned {len(competitors)} competing results, which suggests limited easy headroom.")
    if word_count < 250:
        score -= 8
        risks.append("Thin crawlable copy gives search systems less reason to rank or quote the page.")
    if google_ai_score < 65:
        score -= 6
        risks.append("Google AI/Search readiness is weak, which reduces the chance of being retrieved or cited.")

    quality_score = int(content_profile.get("score") or 0)
    if quality_score >= 75:
        score += 8
    elif quality_score >= 55:
        score += 4
    else:
        score -= 5
        risks.append("The page lacks enough non-commodity signals to stand out from generic web content.")

    moat_signals: list[str] = []
    if is_brand:
        score += 12
        moat_signals.append("brand demand")
    if has_original or has_tool_schema:
        score += 12
        moat_signals.append("original data/tool/research")
        levers.append("Push the tool, data, methodology or source-backed angle harder; that is the part generic answers cannot fully replace.")
    if has_local or has_local_schema:
        score += 8
        moat_signals.append("local specificity")
        levers.append("Strengthen local proof: service area, reviews, photos, prices, case studies and business details.")
    if external_links >= 2:
        score += 3
        moat_signals.append("source links")
    if not moat_signals:
        risks.append("There is no obvious traffic moat such as brand demand, original data, a tool, local specificity or strong source evidence.")
        levers.append("Add something worth seeking out directly: original data, a calculator/checker, a named case study, or a sharp proprietary point of view.")

    if not is_brand and not (has_original or has_tool_schema or has_local or has_local_schema):
        score = min(score, 34)
    if has_commercial and not is_brand and not (has_local or has_local_schema):
        score = min(score, 28)
    if has_informational and not (has_original or has_tool_schema):
        score = min(score, 24)

    score = max(0, min(70, score))
    if score <= 8:
        band = "near zero"
        expected = "Expect incidental long-tail traffic at best unless another channel creates demand."
    elif score <= 20:
        band = "very low"
        expected = "Expect low and volatile organic traffic; useful for credibility, not as the main growth engine."
    elif score <= 35:
        band = "low"
        expected = "Some organic traffic is possible, but it needs a moat, links, brand demand or long-tail accumulation."
    elif score <= 50:
        band = "defensible niche"
        expected = "Organic can contribute if the page has a real moat and Search Console shows impressions to build from."
    else:
        band = "rare organic upside"
        expected = "Organic has unusual upside because the page appears to have brand, local, tool or original-research demand."
    summary = (
        f"Organic traffic outlook is {band} ({score}/100). The page looks like a {page_type}; "
        "the open web is structurally hostile to passive SEO because ads, answer surfaces and AI summaries absorb a lot of demand."
    )
    return {
        "score": score,
        "band": band,
        "page_type": page_type,
        "summary": summary,
        "expected": expected,
        "ads_risk": ads_risk,
        "ai_answer_risk": ai_answer_risk,
        "moat_signals": moat_signals,
        "risks": risks[:6],
        "levers": levers[:6],
        "assumptions": [
            "This is a conservative open-web forecast, not a keyword-volume estimate.",
            "Search Console impressions should replace this heuristic once the page has data.",
            f"Market assumed: {market or 'unspecified'}.",
        ],
    }


def clean_serp_text(value: Any) -> str:
    text = html.unescape(str(value or ""))
    text = re.sub(r"<[^>]+>", "", text)
    return re.sub(r"\s+", " ", text).strip()


def brave_search(search_query: str, target_host: str) -> tuple[list[dict[str, str]], str]:
    load_runtime_env()
[redacted secret-like line]
    if not key:
        return [], "No Brave Search key available on this service."
    if not search_query.strip():
        return [], "No query supplied for competitor search."
    params = urlencode({"q": search_query, "count": "10", "search_lang": "en", "safesearch": "moderate"})
    req = Request(
        f"https://api.search.brave.com/res/v1/web/search?{params}",
        headers={
            "Accept": "application/json",
[redacted secret-like line]
            "User-Agent": "CopeCheckSEO/1.0 (+https://seo.copecheck.com/)",
        },
    )
    try:
        with urlopen(req, timeout=8) as response:
            payload = json.loads(response.read(400_000).decode("utf-8", errors="ignore"))
    except Exception as exc:
        return [], f"Competitor search unavailable: {exc}"

    results = payload.get("web", {}).get("results") if isinstance(payload, dict) else []
    competitors: list[dict[str, str]] = []
    target = target_host.lower().removeprefix("www.")
    for result in results or []:
        if not isinstance(result, dict):
            continue
        url = str(result.get("url") or "")
        parsed = urlparse(url)
        host = (parsed.hostname or "").lower().removeprefix("www.")
        if not host or host == target:
            continue
        competitors.append(
            {
                "rank": str(len(competitors) + 1),
                "title": clean_serp_text(result.get("title") or host),
                "url": url,
                "host": host,
                "snippet": clean_serp_text(result.get("description") or result.get("snippet") or ""),
            }
        )
        if len(competitors) >= 8:
            break
    return competitors, "Brave Search API"


def deterministic_opportunities(
    score: int,
    checks: list[dict[str, Any]],
    competitors: list[dict[str, str]],
    query: str,
) -> dict[str, Any]:
    failed = [check for check in checks if not check.get("ok")]
    urgent = failed[:4]
    competitor_hosts = ", ".join(item["host"] for item in competitors[:4]) or "the current SERP"
    if not failed:
        summary = f"This page scores {score}/100. The technical base is strong, so the next gains come from sharper positioning, fresher evidence and better comparison against the live SERP."
    else:
        summary = f"This page scores {score}/100. The quickest route to a better result is fixing the failed technical and AI-crawl checks before adding more content."
    fixes = [
        {
            "title": str(check.get("label")),
            "reason": str(check.get("detail")),
            "action": str(check.get("recommendation")),
        }
        for check in urgent
    ]
    return {
        "summary": summary,
        "competitor_angle": f"For '{query}', compare the page against {competitor_hosts} and make the answer more specific, better sourced and easier to quote.",
        "content_gaps": [
            "Add a concise answer section near the top of the page.",
            "Add evidence, examples, pricing, locations or use-cases that make the page harder to replace with generic AI output.",
            "Add internal links to the most relevant supporting pages.",
        ],
        "suggested_pages": [
            "A comparison page for the main search intent.",
            "A source-backed FAQ page answering objections and long-tail searches.",
            "A short glossary or explainer page that can attract informational links.",
        ],
        "priority_fixes": fixes,
    }


def minimax_opportunity_summary(
    score: int,
    checks: list[dict[str, Any]],
    competitors: list[dict[str, str]],
    query: str,
    market: str,
) -> tuple[dict[str, Any], str]:
    load_runtime_env()
[redacted secret-like line]
    if not key:
        return deterministic_opportunities(score, checks, competitors, query), "rules"
    failed = [
        {
            "label": check.get("label"),
            "severity": check.get("severity"),
            "detail": check.get("detail"),
            "recommendation": check.get("recommendation"),
        }
        for check in checks
        if not check.get("ok")
    ][:8]
    prompt = {
        "score": score,
        "market": market,
        "query": query,
        "failed_checks": failed,
        "competitors": competitors[:8],
        "required_json": {
            "summary": "one sharp paragraph",
            "competitor_angle": "one paragraph",
            "content_gaps": ["3 to 5 gap strings"],
            "suggested_pages": ["3 to 5 page ideas"],
            "priority_fixes": [{"title": "short", "reason": "short", "action": "specific"}],
        },
    }
    payload = {
        "model": os.getenv("MINIMAX_MODEL", "MiniMax-M2.7"),
        "messages": [
            {
                "role": "system",
                "content": "You are an SEO strategist. Return strict JSON only. Be direct, useful and commercially actionable.",
            },
            {"role": "user", "content": json.dumps(prompt, ensure_ascii=False)},
        ],
        "temperature": 0.2,
[redacted secret-like line]
        "stream": False,
        "reasoning_split": True,
    }
    timeout = float(os.getenv("MINIMAX_TIMEOUT", "7"))
    total_timeout = float(os.getenv("MINIMAX_TOTAL_TIMEOUT", "8"))
    deadline = time.perf_counter() + max(1.0, total_timeout)
    primary_endpoint = os.getenv("MINIMAX_CHAT_ENDPOINT", "https://api.minimax.io/v1/text/chatcompletion_v2")
    endpoints = [primary_endpoint]
    if os.getenv("MINIMAX_TRY_FALLBACK_ENDPOINTS") == "1":
        endpoints.extend(
            [
                "https://api.minimax.io/v1/text/chatcompletion_v2",
                "https://minimax-m2.com/api/v1/chat/completions",
                "https://api.minimax.io/v1/chat/completions",
                "https://api.minimaxi.chat/v1/chat/completions",
            ]
        )
    headers = {
[redacted secret-like line]
        "Content-Type": "application/json",
    }
    last_error = ""
    for endpoint in dict.fromkeys(endpoints):
        remaining = deadline - time.perf_counter()
        if remaining <= 0:
            last_error = f"MiniMax enrichment exceeded {total_timeout:.1f}s total deadline"
            break
        try:
            req = Request(endpoint, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
            with urlopen(req, timeout=min(timeout, max(1.0, remaining))) as response:
                data = json.loads(response.read(500_000).decode("utf-8", errors="ignore"))
            content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
            if not content:
                content = data.get("reply") or data.get("text") or data.get("output_text") or ""
            if isinstance(content, list):
                content = "\n".join(str(item.get("text", item)) for item in content)
            clean_content = re.sub(r"^```(?:json)?", "", str(content).strip(), flags=re.I).removesuffix("```").strip()
            if "{" in clean_content and "}" in clean_content:
                clean_content = clean_content[clean_content.find("{") : clean_content.rfind("}") + 1]
            parsed = json.loads(clean_content)
            if isinstance(parsed, dict):
                fallback = deterministic_opportunities(score, checks, competitors, query)
                fallback.update({key: value for key, value in parsed.items() if value})
                return fallback, f"MiniMax {payload['model']}"
        except Exception as exc:
            last_error = str(exc)
            continue
    fallback = deterministic_opportunities(score, checks, competitors, query)
    fallback["diagnostic"] = f"MiniMax fallback used: {last_error}"
    return fallback, "rules"


def rate_limit_ok(client_id: str) -> tuple[bool, int]:
    now = time.time()
    with AUDIT_LOCK:
        recent = [stamp for stamp in AUDIT_RATE_STORE.get(client_id, []) if stamp > now - AUDIT_RATE_WINDOW]
        allowed = len(recent) < AUDIT_RATE_LIMIT
        if allowed:
            recent.append(now)
        AUDIT_RATE_STORE[client_id] = recent
    return allowed, max(0, AUDIT_RATE_LIMIT - len(AUDIT_RATE_STORE.get(client_id, [])))


def feedback_rate_limit_ok(client_id: str) -> tuple[bool, int]:
    now = time.time()
    with FEEDBACK_LOCK:
        recent = [stamp for stamp in FEEDBACK_RATE_STORE.get(client_id, []) if stamp > now - FEEDBACK_RATE_WINDOW]
        allowed = len(recent) < FEEDBACK_RATE_LIMIT
        if allowed:
            recent.append(now)
        FEEDBACK_RATE_STORE[client_id] = recent
    return allowed, max(0, FEEDBACK_RATE_LIMIT - len(FEEDBACK_RATE_STORE.get(client_id, [])))


def truncate_feedback(value: Any, limit: int = 2200) -> str:
    text = re.sub(r"\s+", " ", str(value or "")).strip()
    return text[:limit]


def save_feedback(payload: dict[str, Any], client_id: str, user_agent: str = "") -> dict[str, Any]:
    message = truncate_feedback(payload.get("message"), 4000)
    if len(message) < 3:
        raise ValueError("Please add a little feedback before sending.")
    audit_context = payload.get("audit")
    if not isinstance(audit_context, dict):
        audit_context = {}
    audit_summary = {
        "url": truncate_feedback(audit_context.get("url"), 500),
        "host": truncate_feedback(audit_context.get("host"), 180),
        "score": audit_context.get("score"),
        "grade": truncate_feedback(audit_context.get("grade"), 8),
        "query": truncate_feedback((audit_context.get("search") or {}).get("query") if isinstance(audit_context.get("search"), dict) else "", 220),
    }
    feedback_id = hashlib.sha1(f"{client_id}|{time.time()}|{message}".encode("utf-8")).hexdigest()[:12]
    record = {
        "id": feedback_id,
        "submitted_at": utc_now(),
        "client_id_hash": hashlib.sha1(client_id.encode("utf-8")).hexdigest()[:12],
        "type": truncate_feedback(payload.get("type"), 60) or "general",
        "message": message,
        "email": truncate_feedback(payload.get("email"), 180),
        "page_url": truncate_feedback(payload.get("page_url"), 700),
        "page_title": truncate_feedback(payload.get("page_title"), 240),
        "audit": audit_summary,
        "user_agent": truncate_feedback(user_agent, 300),
    }
    FEEDBACK_FILE.parent.mkdir(parents=True, exist_ok=True)
    with FEEDBACK_LOCK:
        with FEEDBACK_FILE.open("a", encoding="utf-8") as handle:
            handle.write(json.dumps(record, ensure_ascii=False) + "\n")
    return {"id": feedback_id, "submitted_at": record["submitted_at"]}


def run_seo_audit(raw_url: str, query: str = "", market: str = "United Kingdom") -> dict[str, Any]:
    audit_url = normalise_audit_url(raw_url)
    parsed = urlparse(audit_url)
    host = parsed.hostname or ""
    origin = f"{parsed.scheme}://{parsed.netloc}"
    page = request_url(audit_url, "GET", timeout=18)
    parser = parse_html_document(page)
    robots = request_url(urljoin(origin, "/robots.txt"), "GET", timeout=8)
    sitemap = request_url(urljoin(origin, "/sitemap.xml"), "GET", timeout=8)
    llms = request_url(urljoin(origin, "/llms.txt"), "GET", timeout=8)
    sitemap_urls, sitemap_lastmod = count_sitemap_urls(sitemap.get("body") or b"")
    robots_body = decode_body(robots)
    path_for_robots = parsed.path or "/"
    description = first_meta(parser, "description")
    robots_meta = ",".join(
        value
        for value in [first_meta(parser, "robots"), first_meta(parser, "googlebot")]
        if value
    ).lower()
    x_robots = header_get(page.get("headers") if isinstance(page.get("headers"), dict) else {}, "x-robots-tag").lower()
    canonical = link_rel(parser, "canonical")
    viewport = first_meta(parser, "viewport")
    og_title = first_meta(parser, prop="og:title")
    og_description = first_meta(parser, prop="og:description")
    h1s = parser.headings.get("h1", [])
    text = re.sub(r"\s+", " ", " ".join(parser.body_chunks)).strip()
    word_count = len(re.findall(r"\b[\w'-]+\b", text))
    images_total = len(parser.images)
    images_with_alt = sum(1 for image in parser.images if image.get("alt", "").strip())
    videos_total = len(parser.videos)
    internal_links = 0
    external_links = 0
    for anchor in parser.anchors:
        href = anchor.get("href", "").strip()
        if not href or href.startswith(("#", "mailto:", "tel:")):
            continue
        linked = urlparse(urljoin(origin, href))
        if (linked.hostname or "").lower().removeprefix("www.") == host.lower().removeprefix("www."):
            internal_links += 1
        else:
            external_links += 1
    schema_types = extract_schema_types(parser)
    snippet = snippet_policy(robots_meta, x_robots, parser.data_nosnippet_count)
    content_profile = content_quality_profile(parser, text, word_count, external_links, schema_types)
    agentic_profile = build_agentic_profile(parser, int(llms["status"] or 0), bool(llms["ok"]))
    ai_policy = {
        crawler: {
            "allowed": allowed,
            "detail": detail,
        }
        for crawler in AI_CRAWLERS
        for allowed, detail in [robots_allows(robots_body, crawler, path_for_robots)]
    }
    ai_allowed_count = sum(1 for policy in ai_policy.values() if policy["allowed"])
    default_robot_allowed, default_robot_detail = robots_allows(robots_body, "*", path_for_robots)
    googlebot_allowed, googlebot_detail = robots_allows(robots_body, "Googlebot", path_for_robots)
    robots_sitemaps = robots_sitemap_directives(robots_body)
    cloudflare_robots = cloudflare_robots_diagnostics(robots, robots_body, ai_policy)
    page_indexable = "noindex" not in robots_meta and "none" not in robots_meta and "noindex" not in x_robots and "none" not in x_robots
    google_ai_eligible = bool(page["ok"]) and googlebot_allowed and page_indexable and snippet["allowed"]
    checks: list[dict[str, Any]] = []
    add_audit_check(checks, "technical", "Page returns a successful status", bool(page["ok"]), "critical", f"HTTP {page['status'] or 'offline'} in {page['elapsed_ms']}ms.", "Make the audited URL return a stable 200 response.")
    add_audit_check(checks, "technical", "HTTPS is in use", parsed.scheme == "https", "high", f"Audited scheme is {parsed.scheme}.", "Redirect all public pages to HTTPS.")
    add_audit_check(checks, "technical", "Mobile viewport is declared", bool(viewport), "medium", "Viewport meta tag found." if viewport else "No viewport meta tag was found.", "Add a standard viewport meta tag for mobile rendering.")
    add_audit_check(checks, "indexability", "Page is indexable", page_indexable, "critical", f"Meta robots: {robots_meta or 'none'}; X-Robots-Tag: {x_robots or 'none'}", "Remove noindex/none unless this page is intentionally private.")
    add_audit_check(checks, "indexability", "Robots.txt is readable", robots["status"] in {200, 404}, "medium", f"robots.txt returned HTTP {robots['status'] or 'offline'}.", "Serve robots.txt with a clear sitemap declaration.")
    add_audit_check(checks, "indexability", "Default crawler is allowed by robots.txt", default_robot_allowed, "high", default_robot_detail, "Do not block the audited path for User-agent: * unless the page is intentionally private.")
    add_audit_check(checks, "indexability", "Googlebot is allowed by robots.txt", googlebot_allowed, "critical", googlebot_detail, "Allow Googlebot to crawl the page path.")
    add_audit_check(checks, "indexability", "Robots.txt declares a sitemap", bool(robots_sitemaps), "low", f"{len(robots_sitemaps)} sitemap directive(s) found." if robots_sitemaps else "No Sitemap directive found in robots.txt.", "List the canonical sitemap URL in robots.txt so crawlers can discover it quickly.")
    add_audit_check(checks, "indexability", "Sitemap is readable", bool(sitemap["ok"]) and sitemap_urls > 0, "high", f"sitemap.xml returned HTTP {sitemap['status'] or 'offline'} with {sitemap_urls} URL(s).", "Publish a sitemap.xml and list canonical indexable URLs.")
    add_audit_check(checks, "indexability", "Canonical URL is declared", bool(canonical), "medium", f"Canonical: {canonical or 'missing'}.", "Add a self-referencing canonical unless another canonical is intentional.")
    add_audit_check(checks, "content", "Title length is usable", 12 <= len(parser.title) <= 70, "medium", f"Title is {len(parser.title)} characters.", "Write a clear title between roughly 12 and 70 characters.")
    add_audit_check(checks, "content", "Meta description is usable", 70 <= len(description) <= 170, "medium", f"Description is {len(description)} characters.", "Write a specific search snippet between roughly 70 and 170 characters.")
    add_audit_check(checks, "content", "Single clear H1", len(h1s) == 1, "medium", f"Found {len(h1s)} H1 tag(s).", "Use one primary H1 that states the page topic.")
    add_audit_check(checks, "content", "Enough crawlable text", word_count >= 250, "medium", f"Detected about {word_count} words of crawlable body text.", "Add enough original copy for search and AI systems to understand the page.")
    add_audit_check(checks, "content", "Image alt text coverage", images_total == 0 or images_with_alt / images_total >= 0.75, "low", f"{images_with_alt}/{images_total} images have alt text.", "Add descriptive alt text to meaningful images.")
    add_audit_check(checks, "content", "Structured data present", bool(schema_types), "low", f"Schema types: {', '.join(schema_types) if schema_types else 'none'}.", "Add JSON-LD such as WebPage, Article, FAQPage, LocalBusiness or Product where relevant.")
    add_audit_check(checks, "content", "Social preview metadata present", bool(og_title and og_description), "low", "Open Graph title and description found." if og_title and og_description else "Open Graph title/description is incomplete.", "Add Open Graph and Twitter card metadata so shared links look intentional.")
    add_audit_check(checks, "ai", "AI search crawlers can read the page", ai_allowed_count >= 5, "high", f"{ai_allowed_count}/{len(AI_CRAWLERS)} checked AI/search crawlers appear allowed.", "Do not accidentally block GPTBot, OAI-SearchBot, ClaudeBot or PerplexityBot if AI discovery matters.")
    add_audit_check(checks, "ai", "Cloudflare edge is not hiding AI crawler blocks", not cloudflare_robots["hidden_ai_block_risk"], "high", cloudflare_robots["detail"], "Check the public Cloudflare edge robots.txt response and disable managed AI crawler blocks when AI discovery matters.")
    add_audit_check(checks, "ai", "Robots content signals allow AI search", not (cloudflare_robots["search_blocked"] or cloudflare_robots["ai_input_blocked"]), "medium", cloudflare_robots["content_signal_summary"], "Keep search and ai-input content signals open for pages that should be found and quoted by AI search systems.")
    add_audit_check(checks, "ai", "llms.txt fetch does not server-error", bool(agentic_profile["llms_fetch_ok"]), "low", agentic_profile["llms_detail"], "Fix 5xx/offline llms.txt responses. A 404 is optional for Lighthouse today, but a clean 200 Markdown summary is useful for agents.")
    add_audit_check(checks, "agentic", "Agentic accessibility tree basics", agentic_profile["status"] == "ready", "low", agentic_profile["detail"], "Use semantic landmarks, labelled controls and stable visible UI so browser agents can understand and operate the page.")
    add_audit_check(checks, "agentic", "Static WebMCP tool hints", agentic_profile["webmcp_status"] in {"present", "not_applicable"}, "low", agentic_profile["webmcp_detail"], "For action-heavy pages, expose forms/actions with WebMCP tool names and descriptions or validate dynamic registration in Lighthouse.")
    add_audit_check(checks, "google_ai", "Eligible for Google AI Search features", google_ai_eligible, "critical", f"Search eligibility: HTTP {page['status'] or 'offline'}, Googlebot {'allowed' if googlebot_allowed else 'blocked'}, indexable {'yes' if page_indexable else 'no'}, snippet {'allowed' if snippet['allowed'] else 'blocked'}.", "Make the page indexable, crawlable by Googlebot and eligible for snippets; Google AI features are grounded in the normal Search index.")
    add_audit_check(checks, "google_ai", "Snippet controls allow grounding", snippet["allowed"], "high", snippet["detail"], "Remove nosnippet or max-snippet:0 if you want the page to be usable in Google AI Overviews or AI Mode.")
    add_audit_check(checks, "google_ai", "Non-commodity content signals are present", content_profile["score"] >= 55, "medium", content_profile["detail"], "Add first-hand detail, source-backed evidence, named examples, data, dates, methodology or a clear point of view.")
    add_audit_check(checks, "google_ai", "Query fan-out is answerable on the page", word_count >= 350 and len(parser.headings.get("h2", [])) >= 2, "medium", f"Detected {word_count} words and {len(parser.headings.get('h2', []))} H2 heading(s).", "Use the fan-out planner to cover adjacent user intents inside the page without creating thin doorway pages.")
    add_audit_check(checks, "google_ai", "Browser-agent structure is readable", agentic_profile["status"] == "ready", "low", agentic_profile["detail"], "Use readable semantic landmarks, visible controls and labelled form fields so browser agents and assistive tech can operate the page.")

    failed_weight = sum(
        AUDIT_SEVERITY_WEIGHT.get(str(check["severity"]), 4)
        for check in checks
        if not check["ok"]
    )
    score = max(0, min(100, 100 - failed_weight))
    search_query = (query or derive_search_query(parser, host)).strip()
    competitor_query = f"{search_query} {market}".strip()
    competitors, search_provider = brave_search(competitor_query, host)
    opportunities, summary_provider = minimax_opportunity_summary(score, checks, competitors, search_query, market)
    categories = category_scores(checks)
    google_ai = build_google_ai_readiness(
        categories.get("google_ai", 0),
        search_query,
        market,
        google_ai_eligible,
        snippet,
        content_profile,
        agentic_profile,
        images_total,
        videos_total,
        schema_types,
    )
    traffic_outlook = build_organic_traffic_outlook(
        audit_url,
        host,
        search_query,
        market,
        parser,
        text,
        word_count,
        external_links,
        competitors,
        schema_types,
        bool(page["ok"]),
        page_indexable,
        googlebot_allowed,
        snippet["allowed"],
        google_ai.get("score", categories.get("google_ai", 0)),
        content_profile,
    )
    categories["traffic"] = traffic_outlook["score"]
    audit_id = hashlib.sha1(f"{audit_url}|{time.time()}".encode("utf-8")).hexdigest()[:12]
    summary = opportunities.get("summary") or deterministic_opportunities(score, checks, competitors, search_query)["summary"]
    return {
        "audit_id": audit_id,
        "generated_at": utc_now(),
        "url": audit_url,
        "final_url": page.get("url") or audit_url,
        "host": host,
        "score": score,
        "grade": audit_grade(score),
        "summary": summary,
        "checks": checks,
        "categories": categories,
        "google_ai": google_ai,
        "traffic_outlook": traffic_outlook,
        "facts": {
            "status": page["status"],
            "elapsed_ms": page["elapsed_ms"],
            "content_type": page.get("content_type") or "",
            "title": parser.title,
            "title_length": len(parser.title),
            "description": description,
            "description_length": len(description),
            "h1": h1s[:3],
            "h2_count": len(parser.headings.get("h2", [])),
            "word_count": word_count,
            "canonical": canonical,
            "lang": parser.lang,
            "internal_links": internal_links,
            "external_links": external_links,
            "images_total": images_total,
            "images_with_alt": images_with_alt,
            "videos_total": videos_total,
            "schema_types": schema_types,
            "sitemap_urls": sitemap_urls,
            "sitemap_lastmod": sitemap_lastmod,
            "robots_sitemaps": robots_sitemaps,
            "robots_default_allowed": default_robot_allowed,
            "robots_default_detail": default_robot_detail,
            "x_robots": x_robots,
            "snippet_allowed": snippet["allowed"],
            "data_nosnippet_count": parser.data_nosnippet_count,
            "semantic_landmarks": agentic_profile["landmarks"],
            "llms_status": llms["status"],
            "llms_status_label": agentic_profile["llms_status_label"],
            "llms_detail": agentic_profile["llms_detail"],
            "webmcp_status": agentic_profile["webmcp_status"],
            "webmcp_detail": agentic_profile["webmcp_detail"],
            "webmcp_tools": agentic_profile["webmcp_tools"],
            "robots_status": robots["status"],
            "ai_policy": ai_policy,
            "cloudflare_robots": cloudflare_robots,
        },
        "search": {
            "query": search_query,
            "market": market,
            "competitor_query": competitor_query,
        },
        "competitors": competitors,
        "opportunities": opportunities,
        "provider": {
            "search": search_provider,
            "summary": summary_provider,
        },
    }


def check_site(site: dict[str, str]) -> dict[str, Any]:
    parsed = urlparse(site["url"])
    public_host = (urlparse(PUBLIC_BASE).hostname or "").lower()
    site_host = (parsed.hostname or "").lower()
    if site_host == public_host:
        self_health_url = os.getenv("COPECHECK_SEO_SELF_HEALTH_URL", "http://127.0.0.1:8106/healthz")
        home = request_url(self_health_url, "GET", timeout=min(FETCH_TIMEOUT, 2.0))
    else:
        home = request_url(site["url"], "HEAD")
    if home["status"] in {0, 405, 403}:
        home = request_url(site["url"], "GET")
    origin = f"{parsed.scheme}://{parsed.netloc}"
    robots = request_url(f"{origin}/robots.txt", "GET")
    sitemap = request_url(f"{origin}/sitemap.xml", "GET")
    sitemap_urls, sitemap_lastmod = count_sitemap_urls(sitemap["body"])
    return {
        **site,
        "home_status": home["status"],
        "home_ok": home["ok"],
        "home_ms": home["elapsed_ms"],
        "robots_status": robots["status"],
        "robots_ok": robots["ok"],
        "sitemap_status": sitemap["status"],
        "sitemap_ok": sitemap["ok"],
        "sitemap_urls": sitemap_urls,
        "sitemap_lastmod": sitemap_lastmod,
        "error": home["error"] or sitemap["error"],
    }


def load_json_url(url: str) -> dict[str, Any] | None:
    response = request_url(url, "GET")
    if not response["ok"]:
        return None
    try:
        return json.loads(response["body"].decode("utf-8", errors="ignore"))
    except json.JSONDecodeError:
        return None


def load_oracle_entries() -> dict[str, Any]:
    data = load_json_url("https://codex.copecheck.com/api/oracle?limit=12")
    if not data:
        return {"count": 0, "entries": [], "ok": False}
    entries = data.get("entries") if isinstance(data.get("entries"), list) else []
    return {"count": int(data.get("count") or len(entries)), "entries": entries[:12], "ok": True}


def load_story_feed() -> dict[str, Any]:
    data = load_json_url("https://codex.copecheck.com/api/stories")
    feed = data.get("feed") if isinstance(data, dict) else {}
    if not isinstance(feed, dict):
        return {"ok": False, "count": 0, "stories": []}
    stories = feed.get("stories") if isinstance(feed.get("stories"), list) else []
    statuses: dict[str, int] = {}
    channels: dict[str, int] = {}
    for story in stories:
        if not isinstance(story, dict):
            continue
        channel = str(story.get("channel") or "unknown")
        channels[channel] = channels.get(channel, 0) + 1
        job = story.get("job") if isinstance(story.get("job"), dict) else {}
        status = str(job.get("status") or "unqueued")
        statuses[status] = statuses.get(status, 0) + 1
    return {
        "ok": True,
        "generated_at": feed.get("generatedAt"),
        "count": int(feed.get("count") or len(stories)),
        "stories": stories[:10],
        "statuses": statuses,
        "channels": channels,
    }


def load_search_snapshot() -> dict[str, Any]:
    path = DATA_DIR / "search-console-snapshot.json"
    if path.exists():
        try:
            data = json.loads(path.read_text(encoding="utf-8"))
            if isinstance(data, dict):
                data.setdefault("status", "connected")
                return data
        except json.JSONDecodeError:
            pass
    return {
        "status": "awaiting_api_export",
        "updated_at": None,
        "totals": {"clicks": 0, "impressions": 0, "ctr": 0, "position": None},
        "properties": [],
        "queries": [],
        "note": "Search Console and Bing Webmaster data are ready to publish here once a scheduled export writes data/search-console-snapshot.json.",
    }


def build_snapshot() -> dict[str, Any]:
    network_sites, registry = load_network_sites()
    with ThreadPoolExecutor(max_workers=8) as pool:
        futures = [pool.submit(check_site, site) for site in network_sites]
        sites = [future.result() for future in as_completed(futures)]
    order = {site["host"]: index for index, site in enumerate(network_sites)}
    sites.sort(key=lambda item: order.get(item["host"], 999))
    oracle = load_oracle_entries()
    stories = load_story_feed()
    search = load_search_snapshot()
    live_count = sum(1 for site in sites if site["home_ok"])
    sitemap_total = sum(int(site.get("sitemap_urls") or 0) for site in sites)
    sitemap_hosts = sum(1 for site in sites if site["sitemap_ok"])
    return {
        "generated_at": utc_now(),
        "registry": {
            "source": registry.get("source") or "curated",
            "generated_at": registry.get("generated_at"),
            "count": len(registry.get("sites") or []),
        },
        "sites": sites,
        "oracle": oracle,
        "stories": stories,
        "search": search,
        "totals": {
            "sites": len(sites),
            "sites_live": live_count,
            "sitemap_hosts": sitemap_hosts,
            "sitemap_urls": sitemap_total,
            "oracle_entries": oracle["count"],
            "rss_stories": stories["count"],
        },
    }


def get_snapshot(force: bool = False) -> dict[str, Any]:
    global SNAPSHOT_REFRESHING
    now = time.time()
    should_refresh_async = False
    with SNAPSHOT_LOCK:
        if not force and SNAPSHOT_CACHE["data"] is not None and SNAPSHOT_CACHE["expires"] > now:
            return SNAPSHOT_CACHE["data"]
        if not force and SNAPSHOT_CACHE["data"] is not None:
            cached = SNAPSHOT_CACHE["data"]
            if not SNAPSHOT_REFRESHING:
                SNAPSHOT_REFRESHING = True
                should_refresh_async = True
            if should_refresh_async:
                threading.Thread(target=refresh_snapshot_cache, daemon=True, name="seo-snapshot-refresh").start()
            return cached
    data = build_snapshot()
    with SNAPSHOT_LOCK:
        SNAPSHOT_CACHE["data"] = data
        SNAPSHOT_CACHE["expires"] = now + CACHE_SECONDS
    return data


def refresh_snapshot_cache() -> None:
    global SNAPSHOT_REFRESHING
    try:
        data = build_snapshot()
        with SNAPSHOT_LOCK:
            SNAPSHOT_CACHE["data"] = data
            SNAPSHOT_CACHE["expires"] = time.time() + CACHE_SECONDS
    finally:
        with SNAPSHOT_LOCK:
            SNAPSHOT_REFRESHING = False


def get_layout_snapshot() -> dict[str, Any]:
    with SNAPSHOT_LOCK:
        cached = SNAPSHOT_CACHE.get("data")
        if isinstance(cached, dict):
            return cached
    sites, registry = load_network_sites()
    return {
        "generated_at": utc_now(),
        "registry": {
            "source": registry.get("source") or "curated",
            "generated_at": registry.get("generated_at"),
            "count": len(registry.get("sites") or []),
        },
        "sites": sites,
        "search": load_search_snapshot(),
        "oracle": {"count": 0, "entries": [], "ok": False},
        "stories": {"ok": False, "count": 0, "stories": []},
        "totals": {
            "sites": len(sites),
            "sites_live": 0,
            "sitemap_hosts": 0,
            "sitemap_urls": 0,
            "oracle_entries": 0,
            "rss_stories": 0,
        },
    }


def status_chip(ok: bool, status: Any) -> str:
    label = f"HTTP {status}" if status else "offline"
    cls = "ok" if ok else "warn"
    return f'<span class="chip {cls}">{escape(label)}</span>'


def metric_card(label: str, value: Any, detail: str, tone: str = "") -> str:
    return f"""
      <a class="metric {tone}" href="#network">
        <span>{escape(label)}</span>
        <strong>{escape(value)}</strong>
        <em>{escape(detail)}</em>
      </a>
    """


def render_nav(active: str) -> str:
    links = [
        ("/", "Dashboard"),
        ("/tool/", "Tool"),
        ("/rationale/", "Rationale"),
        ("/subdomains/", "Subdomains"),
        ("/quality-system/", "Quality"),
        ("/search-progress/", "Progress"),
        ("/search-console-api/", "API"),
        ("/google-ai-search/", "AI Search"),
        ("/updates/", "Updates"),
    ]
    return "\n".join(
        f'<a class="{"active" if path == active else ""}" href="{path}">{label}</a>' for path, label in links
    )


def seo_page_for(path: str) -> dict[str, str] | None:
    return next((page for page in SEO_PAGES if page["path"] == path), None)


def render_related_pages(path: str, snapshot: dict[str, Any]) -> str:
    if not seo_page_for(path):
        return ""
    related_map = {
        "/": ["/tool/", "/google-ai-search/", "/subdomains/", "/search-progress/"],
        "/tool/": ["/google-ai-search/", "/quality-system/", "/search-console-api/", "/subdomains/"],
        "/rationale/": ["/subdomains/", "/quality-system/", "/search-progress/", "/updates/"],
        "/subdomains/": ["/rationale/", "/search-progress/", "/tool/", "/updates/"],
        "/quality-system/": ["/tool/", "/google-ai-search/", "/rationale/", "/search-console-api/"],
        "/search-progress/": ["/search-console-api/", "/subdomains/", "/tool/", "/updates/"],
        "/search-console-api/": ["/search-progress/", "/tool/", "/google-ai-search/", "/subdomains/"],
        "/google-ai-search/": ["/tool/", "/quality-system/", "/search-console-api/", "/updates/"],
        "/updates/": ["/tool/", "/google-ai-search/", "/search-progress/", "/quality-system/"],
    }
    pages_by_path = {page["path"]: page for page in SEO_PAGES}
    related = [pages_by_path[item] for item in related_map.get(path, []) if item in pages_by_path]
    cards = "\n".join(
        f"""
        <a href="{escape(page["path"])}">
          <strong>{escape(page["title"])}</strong>
          <span>{escape(page["description"])}</span>
        </a>
        """
        for page in related
    )
    updated = snapshot.get("generated_at") or utc_now()
    return f"""
  <aside class="related-shell" aria-label="Related SEO pages">
    <div>
      <p class="eyebrow">Related CopeCheck SEO pages</p>
      <h2>Keep crawling the evidence graph</h2>
      <p>These links connect the checker, rationale, subdomain index and public progress layer so search engines and visitors see one coherent system.</p>
      <small>Last refreshed {escape(updated)}</small>
    </div>
    <nav class="related-grid">{cards}</nav>
  </aside>
"""


def schema_graph(path: str, title: str, description: str, canonical: str, snapshot: dict[str, Any]) -> dict[str, Any]:
    site_id = f"{PUBLIC_BASE}/#website"
    org_id = "https://www.copecheck.com/#organization"
    page_id = f"{canonical}#webpage"
    breadcrumbs = [
        {"@type": "ListItem", "position": 1, "name": "CopeCheck SEO Lab", "item": PUBLIC_BASE + "/"},
    ]
    if path != "/":
        breadcrumbs.append({"@type": "ListItem", "position": 2, "name": title, "item": canonical})
    graph: list[dict[str, Any]] = [
        {
            "@type": "Organization",
            "@id": org_id,
            "name": "CopeCheck",
            "url": "https://www.copecheck.com/",
            "sameAs": [PUBLIC_BASE + "/", "https://codex.copecheck.com/"],
        },
        {
            "@type": "WebSite",
            "@id": site_id,
            "name": "CopeCheck SEO Lab",
            "url": PUBLIC_BASE + "/",
            "description": "Public SEO, AI crawler and crawl dashboard for the CopeCheck subdomain network.",
            "publisher": {"@id": org_id},
        },
        {
            "@type": "WebPage",
            "@id": page_id,
            "name": title,
            "url": canonical,
            "description": description,
            "isPartOf": {"@id": site_id},
            "publisher": {"@id": org_id},
            "dateModified": snapshot.get("generated_at") or utc_now(),
            "breadcrumb": {"@id": f"{canonical}#breadcrumb"},
        },
        {
            "@type": "BreadcrumbList",
            "@id": f"{canonical}#breadcrumb",
            "itemListElement": breadcrumbs,
        },
    ]
    if path == "/tool/":
        graph.append(
            {
                "@type": "SoftwareApplication",
                "@id": f"{canonical}#app",
                "name": "Free SEO and AI Crawl Checker",
                "applicationCategory": "BusinessApplication",
                "operatingSystem": "Web",
                "url": canonical,
                "description": description,
                "publisher": {"@id": org_id},
                "offers": {"@type": "Offer", "price": "0", "priceCurrency": "GBP"},
            }
        )
    if path == "/updates/":
        graph.append(
            {
                "@type": "ItemList",
                "@id": f"{canonical}#updates",
                "name": "CopeCheck SEO updates",
                "itemListElement": [
                    {
                        "@type": "ListItem",
                        "position": index + 1,
                        "name": update["title"],
                        "url": PUBLIC_BASE + update["url"],
                    }
                    for index, update in enumerate(SEO_UPDATES)
                ],
            }
        )
    return {"@context": "https://schema.org", "@graph": graph}


def render_feedback_widget() -> str:
    return """
  <button class="feedback-launch" type="button" data-feedback-open>Feedback</button>
  <div class="feedback-modal" data-feedback-modal hidden>
    <button class="feedback-backdrop" type="button" data-feedback-close aria-label="Close feedback"></button>
    <form class="feedback-dialog" data-feedback-form>
      <div class="feedback-head">
        <div>
          <strong>Help improve this SEO tool</strong>
          <span>Send bugs, ideas, confusing bits, or checks you want added.</span>
        </div>
        <button type="button" data-feedback-close aria-label="Close feedback">Close</button>
      </div>
      <label>
        <span>Feedback type</span>
        <select name="type">
          <option value="idea">Idea</option>
          <option value="bug">Bug</option>
          <option value="missing-check">Missing check</option>
          <option value="result-quality">Result quality</option>
          <option value="general">General</option>
        </select>
      </label>
      <label>
        <span>Feedback</span>
        <textarea name="message" required placeholder="What should be changed, added, or explained better?"></textarea>
      </label>
      <label>
        <span>Email, optional</span>
        <input name="email" type="email" placeholder="you@example.com">
      </label>
      <div class="feedback-actions">
        <span data-feedback-status></span>
        <button type="submit">Send feedback</button>
      </div>
    </form>
  </div>
  <script>
  (() => {
    const modal = document.querySelector("[data-feedback-modal]");
    const form = document.querySelector("[data-feedback-form]");
    const status = document.querySelector("[data-feedback-status]");
    const openers = document.querySelectorAll("[data-feedback-open]");
    const closers = document.querySelectorAll("[data-feedback-close]");
    if (!modal || !form) return;
    function esc(value) {
      const node = document.createElement("span");
      node.textContent = value == null ? "" : String(value);
      return node.innerHTML;
    }
    function openModal() {
      modal.hidden = false;
      document.body.classList.add("has-feedback-modal");
      setTimeout(() => form.querySelector("textarea")?.focus(), 30);
    }
    function closeModal() {
      modal.hidden = true;
      document.body.classList.remove("has-feedback-modal");
    }
    function lastAuditContext() {
      try {
        const saved = JSON.parse(localStorage.getItem("copecheckSeoLastAudit") || "{}");
        const audit = saved.audit || null;
        if (!audit) return null;
        return {
          url: audit.url,
          host: audit.host,
          score: audit.score,
          grade: audit.grade,
          search: audit.search || {}
        };
      } catch {
        return null;
      }
    }
    openers.forEach((button) => button.addEventListener("click", openModal));
    closers.forEach((button) => button.addEventListener("click", closeModal));
    document.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && !modal.hidden) closeModal();
    });
    form.addEventListener("submit", async (event) => {
      event.preventDefault();
      const button = form.querySelector("button[type='submit']");
      const payload = {
        type: form.type.value,
        message: form.message.value,
        email: form.email.value,
        page_url: window.location.href,
        page_title: document.title,
        audit: lastAuditContext()
      };
      button.disabled = true;
      status.textContent = "Sending...";
      try {
        const response = await fetch("/api/feedback", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload)
        });
        const data = await response.json();
        if (!response.ok || !data.ok) throw new Error(data.error || "Feedback failed.");
        status.innerHTML = `Saved as <strong>${esc(data.feedback.id)}</strong>`;
        form.message.value = "";
        setTimeout(closeModal, 900);
      } catch (error) {
        status.textContent = error.message;
      } finally {
        button.disabled = false;
      }
    });
  })();
  </script>
"""


def render_layout(path: str, title: str, description: str, body: str, snapshot: dict[str, Any]) -> str:
    canonical = f"{PUBLIC_BASE}{path}"
    footer_sites = snapshot.get("sites") if isinstance(snapshot.get("sites"), list) else load_network_sites()[0]
    footer_links = "".join(
        f'<a href="{escape(site["url"])}">{escape(site["host"])}</a>'
        for site in footer_sites
        if isinstance(site, dict)
    )
    document_title = title if title == "CopeCheck SEO Lab" else f"{title} | CopeCheck SEO Lab"
    related_pages = render_related_pages(path, snapshot)
    schema = schema_graph(path, title, description, canonical, snapshot)
    return f"""<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{escape(document_title)}</title>
  <meta name="description" content="{escape(description)}">
  <meta name="robots" content="index,follow,max-image-preview:large">
  <link rel="canonical" href="{escape(canonical)}">
  <meta property="og:title" content="{escape(title)}">
  <meta property="og:description" content="{escape(description)}">
  <meta property="og:url" content="{escape(canonical)}">
  <meta property="og:type" content="website">
  <meta name="twitter:card" content="summary_large_image">
  <link rel="icon" href="/favicon.ico" type="image/svg+xml">
  <link rel="alternate" type="application/rss+xml" title="CopeCheck SEO updates" href="{PUBLIC_BASE}/feed.xml">
  <link rel="alternate" type="text/plain" title="CopeCheck SEO agent brief" href="{PUBLIC_BASE}/llms.txt">
  <script type="application/ld+json">{json.dumps(schema, ensure_ascii=False)}</script>
  <style>{CSS}.oracle-float {{
  position: fixed;
  left: max(1rem, env(safe-area-inset-left));
  bottom: max(1rem, env(safe-area-inset-bottom));
  z-index: 9998;
  display: inline-flex;
  flex-direction: column;
  gap: 0.15rem;
  padding: 0.72rem 0.92rem;
  border: 1px solid rgba(255, 255, 255, 0.22);
  border-radius: 0.75rem;
  background: rgba(12, 16, 24, 0.9);
  color: #fff;
  text-decoration: none;
  box-shadow: 0 18px 42px rgba(0, 0, 0, 0.28);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  transition: transform 160ms ease, box-shadow 160ms ease, border-color 160ms ease;
}}

.oracle-float:hover,
.oracle-float:focus-visible {{
  transform: translateY(-2px);
  border-color: rgba(255, 255, 255, 0.42);
  box-shadow: 0 22px 54px rgba(0, 0, 0, 0.36);
  color: #fff;
}}

.oracle-float-kicker {{
  font-size: 0.64rem;
  font-weight: 700;
  line-height: 1;
  letter-spacing: 0.08em;
  opacity: 0.72;
  text-transform: uppercase;
}}

.oracle-float-title {{
  font-size: 0.95rem;
  font-weight: 800;
  line-height: 1.1;
}}

@media (max-width: 640px) {{
  .oracle-float {{
    left: 0.75rem;
    right: 0.75rem;
    bottom: 0.75rem;
    width: auto;
    align-items: center;
    text-align: center;
  }}

  .oracle-float-kicker {{
    display: none;
  }}
}}
</style>
</head>
<body>
  <header class="topbar">
    <a class="brand" href="/">
      <span class="brand-mark">CC</span>
      <span><strong>CopeCheck</strong><small>SEO Lab</small></span>
    </a>
    <nav>{render_nav(path)}</nav>
    <a class="top-action" href="/data.json">Live JSON</a>
  </header>
  {body}
  {related_pages}
  {render_feedback_widget()}
  <footer class="footer">
    <div>
      <strong>CopeCheck network</strong>
      <p>Public crawl lab for a network of topic-led subdomains. Last refreshed {escape(snapshot["generated_at"])}.</p>
    </div>
    <div class="footer-links">
      {footer_links}
    </div>
  </footer>
  <a class="oracle-float" href="https://chatgpt.com/g/[redacted]" target="_blank" rel="noopener" aria-label="Ask the Oracle custom GPT">
    <span class="oracle-float-kicker">Custom GPT</span>
    <span class="oracle-float-title">Ask the Oracle</span>
  </a>
</body>
</html>"""


def render_home(snapshot: dict[str, Any]) -> str:
    totals = snapshot["totals"]
    search = snapshot["search"]
    entries = snapshot["oracle"]["entries"]
    metrics = "\n".join(
        [
            metric_card("Live subdomains", f'{totals["sites_live"]}/{totals["sites"]}', "HTTP checks across the network", "green"),
            metric_card("Sitemap URLs", totals["sitemap_urls"], f'{totals["sitemap_hosts"]} hosts with readable sitemaps', "blue"),
            metric_card("Oracle entries", totals["oracle_entries"], "scored entries from the Codex ledger", "gold"),
            metric_card("RSS queue", totals["rss_stories"], "latest fetched candidate stories", "rose"),
        ]
    )
    latest = "\n".join(render_oracle_card(entry) for entry in entries[:6]) or "<p>No Oracle entries found.</p>"
    body = f"""
  <main>
    <section class="hero">
      <div class="hero-copy">
        <h1>CopeCheck SEO Lab</h1>
        <p class="lead">A public build log for the CopeCheck network: subdomain rationale, crawl health, quality gates, live content inventory and the search visibility layer as it comes online.</p>
        <div class="hero-actions">
          <a class="button primary" href="/tool/">Run SEO check</a>
          <a class="button secondary" href="/google-ai-search/">AI Search readiness</a>
          <a class="button secondary" href="/subdomains/">Network index</a>
          <a class="button secondary" href="/quality-system/">Quality system</a>
        </div>
      </div>
      <aside class="hero-panel" aria-label="Network status">
        <div class="panel-header">
          <span>Search layer</span>
          <strong>{escape(str(search.get("status", "unknown")).replace("_", " "))}</strong>
        </div>
        <div class="signal-stack">
          <div><span>Google-ready pages</span><strong>{escape(totals["sitemap_urls"])}</strong></div>
          <div><span>Tunnel target</span><strong>{escape(TUNNEL_TARGET.split(".")[0][:8])}</strong></div>
          <div><span>Data mode</span><strong>crawl + JSON</strong></div>
        </div>
      </aside>
    </section>
    <section class="metrics" id="network">{metrics}</section>
    {render_dashboard_analytics(search)}
    {render_network_section(snapshot)}
    <section class="split">
      <div>
        <h2>Latest linkable Oracle pages</h2>
        <p class="section-copy">The front page links through to the actual published pages on their destination subdomains. This keeps the lab useful without competing with the canonical article pages.</p>
      </div>
      <div class="oracle-grid">{latest}</div>
    </section>
    {render_quality_preview()}
    {render_sources()}
  </main>
"""
    return render_layout("/", "CopeCheck SEO Lab", SEO_PAGES[0]["description"], body, snapshot)


def render_dashboard_analytics(search: dict[str, Any]) -> str:
    totals = search.get("totals") if isinstance(search.get("totals"), dict) else {}
    queries = search.get("queries") if isinstance(search.get("queries"), list) else []
    pages = search.get("pages") if isinstance(search.get("pages"), list) else []
    query_items = "\n".join(
        f"""
        <li>
          <strong>{escape(row.get("query") or row.get("keyword") or "")}</strong>
          <span>{escape(row.get("impressions", 0))} impressions / {escape(row.get("clicks", 0))} clicks</span>
        </li>
        """
        for row in queries[:6]
        if isinstance(row, dict)
    ) or "<li><strong>No query data yet</strong><span>The importer will fill this after the next Search Console export.</span></li>"
    page_items = "\n".join(
        f"""
        <li>
          <strong>{escape(clamp_words(row.get("page"), 8))}</strong>
          <span>{escape(row.get("impressions", 0))} impressions / {escape(row.get("clicks", 0))} clicks</span>
        </li>
        """
        for row in pages[:6]
        if isinstance(row, dict)
    ) or "<li><strong>No page data yet</strong><span>Pages will appear here once Google starts surfacing them.</span></li>"
    return f"""
    <section class="dashboard-analytics" id="search-analytics">
      <div class="section-head">
        <div>
          <h2>Search analytics on the dashboard</h2>
          <p>The headline Search Console numbers now sit on the main dashboard, with the detailed date controls and query history kept on the progress page.</p>
        </div>
        <div class="section-actions">
          <a href="/search-progress/">Full progress</a>
          <a href="/search-console-api/">API plan</a>
        </div>
      </div>
      <div class="analytics-kpis">
        <div><span>Clicks</span><strong>{escape(totals.get("clicks", 0))}</strong></div>
        <div><span>Impressions</span><strong>{escape(totals.get("impressions", 0))}</strong></div>
        <div><span>CTR</span><strong>{escape(totals.get("ctr", 0))}%</strong></div>
        <div><span>Avg position</span><strong>{escape(totals.get("position") or "n/a")}</strong></div>
      </div>
      <div class="analytics-split">
        <article>
          <h3>Queries moving first</h3>
          <ul>{query_items}</ul>
        </article>
        <article>
          <h3>Pages Google is surfacing</h3>
          <ul>{page_items}</ul>
        </article>
      </div>
    </section>
"""


def render_network_section(snapshot: dict[str, Any]) -> str:
    rows = "\n".join(render_site_row(site) for site in snapshot["sites"])
    registry = snapshot.get("registry") if isinstance(snapshot.get("registry"), dict) else {}
    registry_note = ""
    if registry.get("generated_at"):
        registry_note = f" Registry refreshed {escape(registry.get('generated_at'))} from {escape(registry.get('source') or 'registry')}."
    return f"""
    <section class="network-table">
      <div class="section-head">
        <div>
          <h2>Live crawl index</h2>
          <p>Each row is checked from the public web: homepage, robots file and sitemap.{registry_note}</p>
        </div>
        <a class="button secondary" href="/data.json">Export JSON</a>
      </div>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Subdomain</th>
              <th>Topical lane</th>
              <th>Home</th>
              <th>Robots</th>
              <th>Sitemap</th>
              <th>URLs</th>
            </tr>
          </thead>
          <tbody>{rows}</tbody>
        </table>
      </div>
    </section>
"""


def render_site_row(site: dict[str, Any]) -> str:
    sitemap_link = f'{site["url"].rstrip("/")}/sitemap.xml'
    return f"""
      <tr>
        <td><a class="host-link" href="{escape(site["url"])}">{escape(site["host"])}</a><small>{escape(site["label"])}</small></td>
        <td>{escape(site["theme"])}</td>
        <td>{status_chip(bool(site["home_ok"]), site["home_status"])}</td>
        <td>{status_chip(bool(site["robots_ok"]), site["robots_status"])}</td>
        <td><a href="{escape(sitemap_link)}">{status_chip(bool(site["sitemap_ok"]), site["sitemap_status"])}</a></td>
        <td><strong>{escape(site["sitemap_urls"])}</strong></td>
      </tr>
    """


def render_oracle_card(entry: dict[str, Any]) -> str:
    url = entry.get("url") or entry.get("source_url") or "#"
    title = entry.get("claim_summary") or entry.get("source_title") or entry.get("publisher") or "Oracle entry"
    score = entry.get("score", "?")
    channel = entry.get("channel") or "main"
    summary = entry.get("oracle_summary") or entry.get("rationale_short") or ""
    return f"""
      <article class="oracle-card">
        <a href="{escape(url)}">
          <span class="score">{escape(score)}</span>
          <small>{escape(channel)} / {escape(entry.get("publisher") or "source")}</small>
          <h3>{escape(clamp_words(title, 18))}</h3>
          <p>{escape(clamp_words(summary, 26))}</p>
        </a>
      </article>
    """


def render_quality_preview() -> str:
    gates = [
        ("Source first", "New automatically published scores require a source URL, publisher/title metadata and a routeable canonical destination. Historical snapshots without record-level citations are labelled separately."),
        ("Rationale not filler", "The page has to explain the claim, the ignored structural issue, the score and why the page belongs in that channel."),
        ("Review state", "Weak attribution, low confidence or malformed output is flagged rather than blended into the clean archive."),
        ("Subdomain fit", "The route is chosen from the source and result signals, so UK, layoffs and policy material lands in the right topical index."),
    ]
    cards = "\n".join(f"<li><strong>{escape(title)}</strong><span>{escape(copy)}</span></li>" for title, copy in gates)
    return f"""
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>Why this is programmatic, not throwaway scaled content</h2>
          <p>New scored pages pass source, quality and routing gates before publication. Older historical snapshots that lack record-level citations are labelled separately rather than presented as current source-backed evidence.</p>
        </div>
        <a class="button primary" href="/quality-system/">Read the quality system</a>
      </div>
      <ul class="gate-list">{cards}</ul>
    </section>
"""


def render_sources() -> str:
    links = "\n".join(f'<a href="{escape(item["url"])}">{escape(item["label"])}</a>' for item in SOURCE_LINKS)
    return f"""
    <section class="sources">
      <h2>Reference points</h2>
      <p>The public rationale is aligned with current search guidance: helpful source-backed pages, readable sitemaps, clear topical structure and no mass publishing purely to manipulate rankings.</p>
      <div>{links}</div>
    </section>
"""


def render_rationale(snapshot: dict[str, Any]) -> str:
    sites = snapshot.get("sites") if isinstance(snapshot.get("sites"), list) else load_network_sites()[0]
    lanes = "\n".join(
        f"""
        <article>
          <a href="{escape(site["url"])}">{escape(site["host"])}</a>
          <h3>{escape(site["label"])}</h3>
          <p>{escape(site["role"])}</p>
        </article>
        """
        for site in sites
        if isinstance(site, dict)
    )
    body = f"""
  <main>
    <section class="page-hero">
      <h1>Why CopeCheck uses subdomains</h1>
      <p class="lead">The network is not a pile of microsites. It is one methodology split into topic-led indexes so each crawl surface has a clear job.</p>
    </section>
    <section class="copy-band">
      <h2>The strategic reason</h2>
      <p>A single giant site would blur UK politics, layoffs, data pages, career advice and general AI displacement claims into one vague archive. Subdomains let each section build its own sitemap, internal links and topical identity while still feeding the shared CopeCheck methodology.</p>
      <p>This also makes experimentation cleaner. A new lane can be tested, expanded, paused or rebuilt without cluttering the main Oracle or forcing every page into one navigation model.</p>
    </section>
    <section class="lane-grid">{lanes}</section>
    {render_sources()}
  </main>
"""
    return render_layout("/rationale/", "Why CopeCheck Uses Subdomains", SEO_PAGES[1]["description"], body, snapshot)


def render_subdomains(snapshot: dict[str, Any]) -> str:
    body = f"""
  <main>
    <section class="page-hero">
      <h1>CopeCheck network index</h1>
      <p class="lead">A live, linkable registry of every public CopeCheck surface currently known to the SEO lab.</p>
    </section>
    {render_network_section(snapshot)}
  </main>
"""
    return render_layout("/subdomains/", "CopeCheck Network Index", SEO_PAGES[2]["description"], body, snapshot)


def render_quality_system(snapshot: dict[str, Any]) -> str:
    body = f"""
  <main>
    <section class="page-hero">
      <h1>Programmatic content quality system</h1>
      <p class="lead">The goal is not to flood search with generated text. The goal is to turn public claims into structured, attributable, linkable records.</p>
    </section>
    <section class="quality-detail">
      <article>
        <h2>Minimum public record</h2>
        <p>Every publishable result should preserve the source URL, publisher, title, date, claimed person or organisation, attribution strength, score, band, rationale, route target and review state.</p>
      </article>
      <article>
        <h2>Routing beats dropdowns</h2>
        <p>Submitters should paste a URL and get a result. The scoring worker and route detector decide whether the page belongs on the main Oracle, UK, layoffs or another future channel.</p>
      </article>
      <article>
        <h2>Quality gates</h2>
        <p>Malformed JSON, weak attribution, indirect quotes, low confidence or thin source extraction should not become clean public archive pages. They can be shown as reviewed or held back until the evidence is strong enough.</p>
      </article>
      <article>
        <h2>Search-safe posture</h2>
        <p>The pages should be useful as a public evidence index even if search traffic never arrives. That is the dividing line: each page needs a reason to exist beyond ranking.</p>
      </article>
    </section>
    {render_sources()}
  </main>
"""
    return render_layout("/quality-system/", "Programmatic Content Quality System", SEO_PAGES[3]["description"], body, snapshot)


def render_search_trend(search: dict[str, Any]) -> str:
    daily = search.get("daily") if isinstance(search.get("daily"), list) else []
    rows: list[dict[str, Any]] = []
    for row in daily:
        if not isinstance(row, dict) or not re.match(r"^\d{4}-\d{2}-\d{2}$", str(row.get("date") or "")):
            continue
        try:
            clicks = float(row.get("clicks") or 0)
            impressions = float(row.get("impressions") or 0)
        except (TypeError, ValueError):
            continue
        rows.append(
            {
                "date": str(row["date"]),
                "clicks": clicks,
                "impressions": impressions,
                "ctr": float(row.get("ctr") or 0),
                "position": row.get("position"),
            }
        )
    rows.sort(key=lambda item: item["date"])
    if not rows:
        return """
    <section class="quality trend-panel">
      <div class="section-head">
        <div>
          <h2>Clicks and impressions over time</h2>
          <p>Daily Search Console rows will appear here after the next importer run.</p>
        </div>
      </div>
    </section>
"""
    start = rows[0]["date"]
    end = rows[-1]["date"]
    trend_json = json.dumps(rows, ensure_ascii=False).replace("</", "<\\/")
    script = """
    <script>
    (() => {
      const rows = __TREND_ROWS__;
      const startInput = document.getElementById("trend-start");
      const endInput = document.getElementById("trend-end");
      const series = document.getElementById("trend-series");
      const readout = document.getElementById("trend-readout");
      const axis = document.getElementById("trend-axis");
      const presets = document.querySelectorAll("[data-trend-days]");
      const fmt = new Intl.NumberFormat("en-GB");
      const compact = new Intl.NumberFormat("en-GB", { notation: "compact", maximumFractionDigits: 1 });
      const svgWidth = 860;
      const svgHeight = 320;
      const pad = { top: 18, right: 26, bottom: 24, left: 28 };
      const innerWidth = svgWidth - pad.left - pad.right;
      const innerHeight = svgHeight - pad.top - pad.bottom;

      function asDateLabel(value) {
        const date = new Date(value + "T12:00:00Z");
        return new Intl.DateTimeFormat("en-GB", { day: "2-digit", month: "short" }).format(date);
      }

      function filteredRows() {
        const start = startInput.value <= endInput.value ? startInput.value : endInput.value;
        const end = startInput.value <= endInput.value ? endInput.value : startInput.value;
        return rows.filter((row) => row.date >= start && row.date <= end);
      }

      function setPreset(days) {
        const end = rows[rows.length - 1].date;
        const startDate = new Date(end + "T12:00:00Z");
        startDate.setUTCDate(startDate.getUTCDate() - days + 1);
        const start = startDate.toISOString().slice(0, 10);
        startInput.value = start < rows[0].date ? rows[0].date : start;
        endInput.value = end;
        renderTrend();
      }

      function renderTrend() {
        const selected = filteredRows();
        if (!selected.length) {
          series.innerHTML = "";
          readout.innerHTML = "<div><span>No rows</span><strong>0</strong></div>";
          axis.textContent = "No data in that range";
          return;
        }
        const clicks = selected.reduce((sum, row) => sum + row.clicks, 0);
        const impressions = selected.reduce((sum, row) => sum + row.impressions, 0);
        const ctr = impressions ? (clicks / impressions) * 100 : 0;
        const maxImpressions = Math.max(...selected.map((row) => row.impressions), 1);
        const maxClicks = Math.max(...selected.map((row) => row.clicks), 1);
        const step = selected.length > 1 ? innerWidth / (selected.length - 1) : innerWidth;
        const barWidth = Math.max(5, Math.min(28, (innerWidth / selected.length) * 0.58));
        const grid = [0, 0.25, 0.5, 0.75, 1].map((ratio) => {
          const y = pad.top + innerHeight * ratio;
          return `<line class="trend-grid" x1="${pad.left}" y1="${y.toFixed(2)}" x2="${svgWidth - pad.right}" y2="${y.toFixed(2)}"></line>`;
        }).join("");
        const bars = selected.map((row, index) => {
          const x = pad.left + (selected.length === 1 ? innerWidth / 2 : step * index);
          const height = row.impressions / maxImpressions * innerHeight;
          const y = pad.top + innerHeight - height;
          return `<rect class="trend-bar" x="${(x - barWidth / 2).toFixed(2)}" y="${y.toFixed(2)}" width="${barWidth.toFixed(2)}" height="${height.toFixed(2)}"><title>${row.date}: ${fmt.format(row.impressions)} impressions, ${fmt.format(row.clicks)} clicks</title></rect>`;
        }).join("");
        const points = selected.map((row, index) => {
          const x = pad.left + (selected.length === 1 ? innerWidth / 2 : step * index);
          const y = pad.top + innerHeight - (row.clicks / maxClicks * innerHeight);
          return `${x.toFixed(2)},${y.toFixed(2)}`;
        });
        const dots = selected.map((row, index) => {
          const [x, y] = points[index].split(",");
          return `<circle class="trend-dot" cx="${x}" cy="${y}" r="4"><title>${row.date}: ${fmt.format(row.clicks)} clicks</title></circle>`;
        }).join("");
        series.innerHTML = `${grid}${bars}<polyline class="trend-line" points="${points.join(" ")}"></polyline>${dots}`;
        readout.innerHTML = `
          <div><span>Selected clicks</span><strong>${fmt.format(clicks)}</strong></div>
          <div><span>Selected impressions</span><strong>${fmt.format(impressions)}</strong></div>
          <div><span>Selected CTR</span><strong>${ctr.toFixed(2)}%</strong></div>
          <div><span>Peak daily impressions</span><strong>${compact.format(maxImpressions)}</strong></div>
        `;
        axis.innerHTML = `<span>${asDateLabel(selected[0].date)}</span><span>${selected.length} daily rows</span><span>${asDateLabel(selected[selected.length - 1].date)}</span>`;
      }

      startInput.addEventListener("change", renderTrend);
      endInput.addEventListener("change", renderTrend);
      presets.forEach((button) => {
        button.addEventListener("click", () => setPreset(Number(button.dataset.trendDays)));
      });
      renderTrend();
    })();
    </script>
""".replace("__TREND_ROWS__", trend_json)
    return f"""
    <section class="quality trend-panel" id="search-trend">
      <div class="section-head">
        <div>
          <h2>Clicks and impressions over time</h2>
          <p>Daily Search Console data for the selected range.</p>
        </div>
        <span class="chip ok">{escape(len(rows))} daily rows</span>
      </div>
      <div class="trend-controls" aria-label="Search trend date range">
        <label><span>Start</span><input id="trend-start" type="date" min="{escape(start)}" max="{escape(end)}" value="{escape(start)}"></label>
        <label><span>End</span><input id="trend-end" type="date" min="{escape(start)}" max="{escape(end)}" value="{escape(end)}"></label>
        <div class="trend-presets" aria-label="Date presets">
          <button type="button" data-trend-days="7">7 days</button>
          <button type="button" data-trend-days="14">14 days</button>
          <button type="button" data-trend-days="28">28 days</button>
        </div>
      </div>
      <div class="trend-readout" id="trend-readout"></div>
      <div class="trend-chart-wrap">
        <svg id="search-trend-chart" class="trend-chart" viewBox="0 0 860 320" role="img" aria-labelledby="trend-title trend-desc" preserveAspectRatio="none">
          <title id="trend-title">Search clicks and impressions trend</title>
          <desc id="trend-desc">Impressions are shown as blue bars and clicks are shown as a green line for the selected date range.</desc>
          <g id="trend-series"></g>
        </svg>
      </div>
      <div class="trend-axis" id="trend-axis"></div>
      <div class="trend-legend" aria-label="Chart legend">
        <span><i class="legend-bar"></i>Impressions</span>
        <span><i class="legend-line"></i>Clicks</span>
      </div>
    </section>
    {script}
"""


def render_search_progress(snapshot: dict[str, Any]) -> str:
    search = snapshot["search"]
    totals = search.get("totals") if isinstance(search.get("totals"), dict) else {}
    properties = search.get("properties") if isinstance(search.get("properties"), list) else []
    queries = search.get("queries") if isinstance(search.get("queries"), list) else []
    pages = search.get("pages") if isinstance(search.get("pages"), list) else []
    opportunities = search.get("opportunities") if isinstance(search.get("opportunities"), list) else []
    new_query_rows = search.get("new_queries") if isinstance(search.get("new_queries"), list) else []
    errors = search.get("errors") if isinstance(search.get("errors"), list) else []
    prop_rows = "\n".join(
        f"""
        <tr>
          <td>{escape(row.get("property") or row.get("site") or "")}</td>
          <td>{escape(row.get("clicks", 0))}</td>
          <td>{escape(row.get("impressions", 0))}</td>
          <td>{escape(row.get("ctr", 0))}</td>
          <td>{escape(row.get("position", ""))}</td>
        </tr>
        """
        for row in properties
    ) or '<tr><td colspan="5">Awaiting Search Console/Bing export.</td></tr>'
    query_cards = "\n".join(
        f"<li><strong>{escape(row.get('query') or row.get('keyword') or '')}</strong><span>{escape(row.get('impressions', 0))} impressions</span></li>"
        for row in queries[:12]
    ) or "<li><strong>No query data yet</strong><span>Once the API export runs, ranking terms can show here.</span></li>"
    page_cards = "\n".join(
        f"<li><strong>{escape(clamp_words(row.get('page'), 9))}</strong><span>{escape(row.get('impressions', 0))} impressions / {escape(row.get('clicks', 0))} clicks</span></li>"
        for row in pages[:12]
    ) or "<li><strong>No page data yet</strong><span>Pages will appear after the first Search Console import.</span></li>"
    opportunity_cards = "\n".join(
        f"<li><strong>{escape(clamp_words(row.get('page'), 8))}</strong><span>{escape(row.get('impressions', 0))} impressions and no clicks yet</span></li>"
        for row in opportunities[:12]
    ) or "<li><strong>No zero-click opportunities yet</strong><span>This fills when pages get impressions without clicks.</span></li>"
    new_query_cards = "\n".join(
        f"<li><strong>{escape(row.get('query') or '')}</strong><span>first seen {escape(str(row.get('first_seen') or '')[:10])} / {escape(row.get('impressions', 0))} impressions</span></li>"
        for row in new_query_rows[:12]
    ) or "<li><strong>No new queries logged yet</strong><span>The importer tracks first-seen query terms over time.</span></li>"
    error_notice = ""
    if errors:
        error_notice = f"""
    <section class="sources warning">
      <h2>Importer notes</h2>
      <p>{escape(errors[0].get("error") if isinstance(errors[0], dict) else errors[0])}</p>
    </section>
"""
    body = f"""
  <main>
    <section class="page-hero">
      <h1>Public search progress</h1>
      <p><a href="/search-progress/archive-2026-may-august/">Historical archive: complete May–August 2026 figures, chart and CSV</a></p>
      <p class="lead">This is the place for the build-in-public scoreboard: Search Console, Bing Webmaster Tools, sitemap growth and public crawl health.</p>
    </section>
    <section class="metrics">
      {metric_card("Clicks", totals.get("clicks", 0), "from search snapshot", "green")}
      {metric_card("Impressions", totals.get("impressions", 0), "from search snapshot", "blue")}
      {metric_card("CTR", totals.get("ctr", 0), "aggregate", "gold")}
      {metric_card("Avg position", totals.get("position") or "n/a", "aggregate", "rose")}
    </section>
    {render_search_trend(search)}
    <section class="network-table">
      <div class="section-head">
        <div>
          <h2>Search property snapshot</h2>
          <p>{escape(search.get("note") or "Latest public search export.")}</p>
        </div>
        <span class="chip ok">{escape(str(search.get("status", "unknown")).replace("_", " "))}</span>
      </div>
      <div class="table-wrap">
        <table>
          <thead><tr><th>Property</th><th>Clicks</th><th>Impressions</th><th>CTR</th><th>Position</th></tr></thead>
          <tbody>{prop_rows}</tbody>
        </table>
      </div>
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>Ranking terms to watch</h2>
          <p>These should become the public proof of what the project is learning as pages get indexed.</p>
        </div>
      </div>
      <ul class="gate-list">{query_cards}</ul>
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>Pages getting search impressions</h2>
          <p>These are the URLs Google is actually surfacing. The useful split is by subdomain, not just total traffic.</p>
        </div>
      </div>
      <ul class="gate-list">{page_cards}</ul>
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>Zero-click opportunities</h2>
          <p>Pages with impressions but no clicks are the first candidates for title, description, internal-link, or content upgrades.</p>
        </div>
      </div>
      <ul class="gate-list">{opportunity_cards}</ul>
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>New queries first seen</h2>
          <p>This is the build-out signal: fresh query surfaces appearing as new pages and subdomains enter the index.</p>
        </div>
      </div>
      <ul class="gate-list">{new_query_cards}</ul>
    </section>
    {error_notice}
  </main>
"""
    return render_layout("/search-progress/", "Public Search Progress", SEO_PAGES[4]["description"], body, snapshot)


def render_search_console_api(snapshot: dict[str, Any]) -> str:
    search = snapshot["search"]
    totals = search.get("totals") if isinstance(search.get("totals"), dict) else {}
    properties = search.get("properties") if isinstance(search.get("properties"), list) else []
    api_links = "".join(
        f'<a href="{escape(link["url"])}">{escape(link["label"])}</a>'
        for link in SEARCH_CONSOLE_API_LINKS
    )
    api_rows = """
        <tr>
          <td><strong>Sites</strong></td>
          <td>List, add, remove and read Search Console properties available to the authorised account.</td>
          <td>Inventory and permission checks for the CopeCheck domain and subdomain estate.</td>
        </tr>
        <tr>
          <td><strong>Sitemaps</strong></td>
          <td>Submit, list, inspect and delete sitemap submissions for verified properties.</td>
          <td>Notify Google when the network sitemap layer changes without using the deprecated ping endpoint.</td>
        </tr>
        <tr>
          <td><strong>Search Analytics</strong></td>
          <td>Pull clicks, impressions, CTR and position by date, query, page, country and device.</td>
          <td>Power the public progress charts and opportunity lists without exposing raw credentials.</td>
        </tr>
        <tr>
          <td><strong>URL Inspection</strong></td>
          <td>Inspect selected URLs for indexed status, canonical choice and crawl/index diagnostics.</td>
          <td>Spot which generated pages Google has accepted, ignored, canonicalised or not crawled yet.</td>
        </tr>
    """
    body = f"""
  <main>
    <section class="page-hero">
      <h1>Search Console API control plane</h1>
      <p class="lead">CopeCheck can manage the practical Search Console loop by API: sitemap submission, URL inspection, search analytics import and public progress reporting. Verification and credentials stay outside the public site.</p>
    </section>
    <section class="metrics">
      <div class="metric green">
        <span>API status</span>
        <strong>{escape(str(search.get("status", "unknown")).replace("_", " "))}</strong>
        <em>from public snapshot</em>
      </div>
      <div class="metric blue">
        <span>Tracked properties</span>
        <strong>{escape(len(properties))}</strong>
        <em>in the latest export</em>
      </div>
      <div class="metric gold">
        <span>Clicks</span>
        <strong>{escape(totals.get("clicks", 0))}</strong>
        <em>Search Console snapshot</em>
      </div>
      <div class="metric rose">
        <span>Impressions</span>
        <strong>{escape(totals.get("impressions", 0))}</strong>
        <em>Search Console snapshot</em>
      </div>
    </section>
    <section class="quality api-flow">
      <div class="section-head">
        <div>
          <h2>Publishing hook</h2>
          <p>When the scoring system publishes a useful page, the search layer should update discovery signals first, then measure what Google does with the page later.</p>
        </div>
      </div>
      <ol class="flow-list">
        <li><strong>Discover</strong><span>The SEO registry refreshes from the live Cloudflare tunnel, so new CopeCheck subdomains enter the crawl dashboard automatically.</span></li>
        <li><strong>Publish</strong><span>A new automatically scored page goes live on the correct CopeCheck subdomain only with a canonical URL, source link and verdict; labelled historical snapshots follow a separate disclosure path.</span></li>
        <li><strong>Update sitemap</strong><span>The relevant sitemap gets an accurate lastmod for the changed URL or sitemap index.</span></li>
        <li><strong>Submit sitemap</strong><span>The Search Console API submits the changed sitemap against the verified domain property.</span></li>
        <li><strong>Inspect later</strong><span>URL Inspection runs after a delay so crawl, canonical and indexing status can be recorded.</span></li>
        <li><strong>Report</strong><span>The private importer writes a sanitized search snapshot for this public SEO lab.</span></li>
      </ol>
    </section>
    <section class="network-table">
      <div class="section-head">
        <div>
          <h2>What can be managed by API</h2>
          <p>The API does not replace every button in Search Console, but it covers the parts CopeCheck needs for a build-in-public crawl and search visibility layer.</p>
        </div>
      </div>
      <div class="table-wrap">
        <table>
          <thead><tr><th>Surface</th><th>API capability</th><th>CopeCheck use</th></tr></thead>
          <tbody>{api_rows}</tbody>
        </table>
      </div>
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>Guardrails</h2>
          <p>The point is to make the network observable without turning the public site into a credential or quota risk.</p>
        </div>
      </div>
      <ul class="gate-list">
        <li><strong>Verification first</strong><span>Adding a property through the API does not prove ownership. DNS, HTML, Analytics or another Search Console verification route still has to exist.</span></li>
        <li><strong>One domain property is enough</strong><span>A verified domain property for copecheck.com is the clean base layer because it covers protocols and subdomains; URL-prefix properties can be added later for more granular reporting.</span></li>
        <li><strong>No old sitemap ping</strong><span>The unauthenticated sitemap ping endpoint is deprecated. CopeCheck should submit sitemaps through Search Console and list them in robots.txt.</span></li>
        <li><strong>No Indexing API abuse</strong><span>The Indexing API is for job posting and livestream pages, not normal Oracle articles or thesis pages.</span></li>
[redacted secret-like line]
      </ul>
    </section>
    <section class="sources">
      <h2>API references</h2>
      <p>These are the Google surfaces this page is designed around.</p>
      <div>{api_links}</div>
    </section>
  </main>
"""
    return render_layout("/search-console-api/", "Search Console API Control Plane", SEO_PAGES[5]["description"], body, snapshot)


def render_audit_tool(snapshot: dict[str, Any]) -> str:
    script = r"""
    <script>
    (() => {
      const form = document.getElementById("audit-form");
      const urlInput = document.getElementById("audit-url");
      const queryInput = document.getElementById("audit-query");
      const marketInput = document.getElementById("audit-market");
      const result = document.getElementById("audit-result");
      const submitButton = document.getElementById("audit-submit");
      const examples = document.querySelectorAll("[data-audit-url]");
      const saved = localStorage.getItem("copecheckSeoLastAudit");

      function esc(value) {
        const node = document.createElement("span");
        node.textContent = value == null ? "" : String(value);
        return node.innerHTML;
      }

      function chip(ok, label) {
        return `<span class="audit-chip ${ok ? "ok" : "warn"}">${esc(label)}</span>`;
      }

      function renderList(values) {
        if (!values || !values.length) return "<li>None detected.</li>";
        return values.map((value) => `<li>${esc(value)}</li>`).join("");
      }

      function yesNo(value) {
        return value ? "yes" : "no";
      }

      function normalizeAuditUrl(value) {
        const raw = String(value || "").trim();
        if (!raw) return "";
        if (/^https?:\/\//i.test(raw)) return raw;
        return `https://${raw}`;
      }

      function auditLinkFor(url, query, market, run = true) {
        const share = new URL("/tool/", window.location.origin);
        share.searchParams.set("url", normalizeAuditUrl(url));
        if (query) share.searchParams.set("query", query);
        if (market) share.searchParams.set("market", market);
        if (run) share.searchParams.set("run", "1");
        return share.toString();
      }

      function domainUrl(host) {
        return `https://${String(host || "").replace(/^https?:\/\//, "").replace(/\/.*$/, "")}/`;
      }

      function renderAudit(audit, restored = false) {
        const failed = audit.checks.filter((check) => !check.ok);
        const shareUrl = auditLinkFor(audit.url, audit.search.query, audit.search.market, true);
        const cloudflareRobots = audit.facts.cloudflare_robots || {};
        const robotsSitemaps = audit.facts.robots_sitemaps || [];
        const categories = Object.entries(audit.categories || {}).map(([label, value]) => `
          <div>
            <span>${esc(label)}</span>
            <strong>${esc(value)}</strong>
          </div>
        `).join("");
        const checks = audit.checks.map((check) => `
          <article class="check-card ${check.ok ? "pass" : "fail"}">
            <div>
              ${chip(check.ok, check.ok ? "pass" : check.severity)}
              <small>${esc(check.category)}</small>
            </div>
            <h3>${esc(check.label)}</h3>
            <p>${esc(check.detail)}</p>
            ${check.ok ? "" : `<strong>${esc(check.recommendation)}</strong>`}
          </article>
        `).join("");
        const competitors = (audit.competitors || []).map((item) => `
          <article>
            <a class="competitor-main" href="${esc(item.url)}">
              <small>#${esc(item.rank)} ${esc(item.host)}</small>
              <h3>${esc(item.title)}</h3>
              <p>${esc(item.snippet)}</p>
            </a>
            <div class="competitor-actions">
              <a href="${esc(item.url)}">Open result</a>
              <a href="${esc(auditLinkFor(domainUrl(item.host), audit.search.query, audit.search.market, true))}">Run on this domain</a>
            </div>
          </article>
        `).join("") || "<p>No live competitors came back for that query. Add a clearer target query and run it again.</p>";
        const opportunity = audit.opportunities || {};
        const fixes = (opportunity.priority_fixes || []).map((fix) => `
          <li>
            <strong>${esc(fix.title)}</strong>
            <span>${esc(fix.reason)} ${esc(fix.action)}</span>
          </li>
        `).join("");
        const googleAi = audit.google_ai || {};
        const googleAiSource = googleAi.source || "https://developers.google.com/search/docs/fundamentals/ai-optimization-guide";
        const contentQuality = googleAi.content_quality || {};
        const eligibility = googleAi.eligibility || {};
        const agentic = googleAi.agentic || {};
        const fanout = (googleAi.fanout_queries || []).map((item) => `
          <li>
            <strong>${esc(item.intent)}: ${esc(item.query)}</strong>
            <span>${esc(item.content_move)}</span>
          </li>
        `).join("");
        const googleAiTools = (googleAi.tools || []).map((tool) => {
          const link = tool.url
            ? `<a href="${esc(tool.url)}">Open docs</a>`
            : tool.name === "PageSpeed Insights follow-up"
            ? `<a href="https://pagespeed.web.dev/analysis?url=${encodeURIComponent(audit.url || "")}">Open PSI</a>`
            : "";
          return `
            <li>
              <strong>${esc(tool.name)} <em>${esc(tool.status)}</em></strong>
              <span>${esc(tool.detail)} ${link}</span>
            </li>
          `;
        }).join("");
        const mythbusters = (googleAi.mythbusters || []).map((item) => `<li>${esc(item)}</li>`).join("");
        const traffic = audit.traffic_outlook || {};
        const trafficRisks = (traffic.risks || []).map((item) => `<li>${esc(item)}</li>`).join("");
        const trafficLevers = (traffic.levers || []).map((item) => `<li>${esc(item)}</li>`).join("");
        const trafficMoats = (traffic.moat_signals || []).length ? traffic.moat_signals.join(", ") : "none obvious";
        result.innerHTML = `
          <section class="audit-results" aria-live="polite">
            ${restored ? `<p class="restored-note">Showing your last audit from this browser. Run it again for a fresh result.</p>` : ""}
            <div class="score-panel">
              <div class="score-ring">
                <span>${esc(audit.grade)}</span>
                <strong>${esc(audit.score)}</strong>
                <small>/100</small>
              </div>
              <div>
                <p class="eyebrow">Live audit result</p>
                <h2>${esc(audit.host)}</h2>
                <p>${esc(audit.summary)}</p>
                <div class="audit-meta">
                  ${chip(failed.length === 0, `${failed.length} issue${failed.length === 1 ? "" : "s"}`)}
                  ${chip(true, `${esc(audit.provider.search)}`)}
                  ${chip(true, `${esc(audit.provider.summary)}`)}
                </div>
                <div class="share-panel">
                  <div>
                    <strong>Share this audit</strong>
                    <span>Opens with this URL, query and market ready to run.</span>
                  </div>
                  <input id="audit-share-url" type="text" value="${esc(shareUrl)}" readonly>
                  <button type="button" data-copy-share>Copy link</button>
                </div>
              </div>
            </div>
            <div class="category-strip">${categories}</div>
            <section class="traffic-outlook-panel">
              <div class="section-head">
                <div>
                  <p class="eyebrow">Open-web traffic forecast</p>
                  <h2>${esc(traffic.band || "unknown")} / ${esc(traffic.score == null ? "n/a" : traffic.score)} score</h2>
                  <p>${esc(traffic.summary || "Organic traffic outlook was not generated.")}</p>
                </div>
              </div>
              <div class="traffic-kpis">
                <div><span>Page type</span><strong>${esc(traffic.page_type || "unknown")}</strong><em>${esc(traffic.expected || "")}</em></div>
                <div><span>Ad pressure</span><strong>${esc(traffic.ads_risk || "unknown")}</strong><em>commercial results are often paid-first</em></div>
                <div><span>Answer risk</span><strong>${esc(traffic.ai_answer_risk || "unknown")}</strong><em>zero-click and AI summary exposure</em></div>
                <div><span>Moat</span><strong>${esc(trafficMoats)}</strong><em>brand, tool, data, local or source-backed advantage</em></div>
              </div>
              <div class="traffic-grid">
                <article>
                  <h3>Why traffic may not arrive</h3>
                  <ul>${trafficRisks || "<li>No major traffic risks detected beyond the usual open-web headwinds.</li>"}</ul>
                </article>
                <article>
                  <h3>What to do instead</h3>
                  <ul>${trafficLevers || "<li>Build non-search distribution and use Search Console data once impressions appear.</li>"}</ul>
                </article>
              </div>
            </section>
            <section class="google-ai-panel">
              <div class="section-head">
                <div>
                  <p class="eyebrow">Google AI Search readiness</p>
                  <h2>${esc(googleAi.status || "unknown")} / ${esc(googleAi.score == null ? "n/a" : googleAi.score)} score</h2>
                  <p>Mapped to Google's guidance: normal Search eligibility, snippet access, useful non-commodity content, query fan-out coverage and agent-friendly page structure.</p>
                </div>
                <div class="section-actions">
                  <a href="${esc(googleAiSource)}">Google guide</a>
                  <a href="/google-ai-search/">How this works</a>
                </div>
              </div>
              <div class="google-ai-kpis">
                <div><span>Eligibility</span><strong>${esc(eligibility.eligible ? "eligible" : "blocked")}</strong><em>${esc(eligibility.detail || "")}</em></div>
                <div><span>Content profile</span><strong>${esc(contentQuality.score == null ? "n/a" : contentQuality.score)}</strong><em>${esc(contentQuality.commodity_risk || "unknown")} commodity risk</em></div>
                <div><span>Agentic UX</span><strong>${esc(agentic.status || "unknown")}</strong><em>${esc(agentic.detail || "")}</em></div>
                <div><span>WebMCP</span><strong>${esc(agentic.webmcp_status || "unknown")}</strong><em>${esc(agentic.webmcp_detail || "")}</em></div>
                <div><span>llms.txt</span><strong>${esc(agentic.llms_status_label || "unknown")}</strong><em>${esc(agentic.llms_detail || "")}</em></div>
              </div>
              <div class="google-ai-grid">
                <article>
                  <h3>Query fan-out planner</h3>
                  <p>Use these as coverage prompts inside the page. Do not spin them into thin pages just because they exist.</p>
                  <ul>${fanout || "<li>No fan-out prompts generated.</li>"}</ul>
                </article>
                <article>
                  <h3>Tools to run next</h3>
                  <ul>${googleAiTools || "<li>No tool recommendations generated.</li>"}</ul>
                </article>
                <article>
                  <h3>Myths to ignore</h3>
                  <ul>${mythbusters || "<li>No myth filters generated.</li>"}</ul>
                </article>
              </div>
            </section>
            <section class="audit-facts">
              <article>
                <h3>Page facts</h3>
                <ul>
                  <li><strong>Status</strong><span>HTTP ${esc(audit.facts.status)} in ${esc(audit.facts.elapsed_ms)}ms</span></li>
                  <li><strong>Title</strong><span>${esc(audit.facts.title || "missing")}</span></li>
                  <li><strong>Description</strong><span>${esc(audit.facts.description || "missing")}</span></li>
                  <li><strong>Words</strong><span>${esc(audit.facts.word_count)}</span></li>
                  <li><strong>Media</strong><span>${esc(audit.facts.images_total)} image(s), ${esc(audit.facts.videos_total || 0)} video element(s)</span></li>
                  <li><strong>Sitemap URLs</strong><span>${esc(audit.facts.sitemap_urls)}</span></li>
                </ul>
              </article>
              <article>
                <h3>Robots and edge</h3>
                <ul>
                  <li><strong>Robots status</strong><span>HTTP ${esc(audit.facts.robots_status)}</span></li>
                  <li><strong>Default crawler</strong><span>${esc(audit.facts.robots_default_allowed ? "allowed" : "blocked")} - ${esc(audit.facts.robots_default_detail || "")}</span></li>
                  <li><strong>Robots sitemap</strong><span>${esc(robotsSitemaps.length ? robotsSitemaps.join(", ") : "missing")}</span></li>
                  <li><strong>Snippet</strong><span>${esc(audit.facts.snippet_allowed ? "allowed" : "blocked")} / data-nosnippet: ${esc(audit.facts.data_nosnippet_count || 0)}</span></li>
                  <li><strong>Cloudflare edge</strong><span>${esc(yesNo(cloudflareRobots.served_by_cloudflare))}${cloudflareRobots.hidden_ai_block_risk ? " - hidden AI block risk" : ""}</span></li>
                  <li><strong>Content signals</strong><span>${esc(cloudflareRobots.content_signal_summary || "No content-signal policy found.")}</span></li>
                </ul>
              </article>
              <article>
                <h3>AI crawler policy</h3>
                <ul>
                  ${Object.entries(audit.facts.ai_policy || {}).map(([name, policy]) => `<li><strong>${esc(name)}</strong><span>${esc(policy.allowed ? "allowed" : "blocked")} - ${esc(policy.detail)}</span></li>`).join("")}
                </ul>
              </article>
              <article>
                <h3>Schema detected</h3>
                <ul>${renderList(audit.facts.schema_types || [])}</ul>
              </article>
            </section>
            <section class="opportunity-panel">
              <div>
                <h2>Commercial angle</h2>
                <p>${esc(opportunity.competitor_angle || "")}</p>
              </div>
              <div>
                <h3>Content gaps</h3>
                <ul>${renderList(opportunity.content_gaps || [])}</ul>
              </div>
              <div>
                <h3>Page ideas</h3>
                <ul>${renderList(opportunity.suggested_pages || [])}</ul>
              </div>
              <div>
                <h3>Priority fixes</h3>
                <ul>${fixes || "<li>No priority fixes returned.</li>"}</ul>
              </div>
            </section>
            <section class="checks-grid">${checks}</section>
            <section class="competitor-list">
              <div class="section-head">
                <div>
                  <h2>Competitors pulled for this query</h2>
                  <p>${esc(audit.search.competitor_query)}</p>
                </div>
              </div>
              <div>${competitors}</div>
            </section>
          </section>
        `;
        const copyButton = result.querySelector("[data-copy-share]");
        const shareInput = result.querySelector("#audit-share-url");
        if (copyButton && shareInput) {
          copyButton.addEventListener("click", async () => {
            try {
              await navigator.clipboard.writeText(shareUrl);
              copyButton.textContent = "Copied";
            } catch (error) {
              shareInput.focus();
              shareInput.select();
              copyButton.textContent = "Select link";
            }
          });
        }
      }

      async function runAudit(payload, options = {}) {
        submitButton.disabled = true;
        submitButton.textContent = "Auditing...";
        result.innerHTML = `<section class="audit-loading"><strong>Running live checks</strong><span>Fetching the page, robots.txt, sitemap, AI crawler rules and competitor SERP.</span></section>`;
        try {
          const response = await fetch("/api/audit", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
          });
          const data = await response.json();
          if (!response.ok || !data.ok) {
            throw new Error(data.error || "Audit failed.");
          }
          localStorage.setItem("copecheckSeoLastAudit", JSON.stringify({ audit: data.audit, savedAt: Date.now() }));
          renderAudit(data.audit);
          if (options.updateHistory !== false) {
            window.history.replaceState({}, "", auditLinkFor(data.audit.url, data.audit.search.query, data.audit.search.market, true));
          }
        } catch (error) {
          result.innerHTML = `<section class="audit-error"><strong>Audit could not run</strong><span>${esc(error.message)}</span></section>`;
        } finally {
          submitButton.disabled = false;
          submitButton.textContent = "Run live audit";
        }
      }

      form.addEventListener("submit", (event) => {
        event.preventDefault();
        urlInput.value = normalizeAuditUrl(urlInput.value);
        runAudit({
          url: urlInput.value.trim(),
          query: queryInput.value.trim(),
          market: marketInput.value.trim() || "United Kingdom",
        });
      });
      examples.forEach((button) => {
        button.addEventListener("click", () => {
          urlInput.value = button.dataset.auditUrl;
          queryInput.value = button.dataset.auditQuery || "";
          marketInput.value = button.dataset.auditMarket || "United Kingdom";
          form.requestSubmit();
        });
      });
      const params = new URLSearchParams(window.location.search);
      const sharedUrl = params.get("url");
      if (sharedUrl) {
        urlInput.value = normalizeAuditUrl(sharedUrl);
        queryInput.value = params.get("query") || "";
        marketInput.value = params.get("market") || "United Kingdom";
        if (params.get("run") === "1") {
          runAudit({
            url: urlInput.value.trim(),
            query: queryInput.value.trim(),
            market: marketInput.value.trim() || "United Kingdom",
          }, { updateHistory: false });
        }
      } else if (saved) {
        try {
          const parsed = JSON.parse(saved);
          if (parsed.audit) renderAudit(parsed.audit, true);
        } catch (error) {
          localStorage.removeItem("copecheckSeoLastAudit");
        }
      }
    })();
    </script>
"""
    body = f"""
  <main>
    <section class="page-hero tool-hero">
      <p class="eyebrow">SEO product surface</p>
      <h1>Free SEO and AI Crawl Checker</h1>
      <p class="lead">Run a live page audit for search visibility, Google AI Search readiness, indexability, sitemap health, AI crawler access and competitor gaps. It is built from the same checks used to debug the CopeCheck network.</p>
    </section>
    <section class="audit-tool">
      <form id="audit-form" class="audit-form" toolname="run_seo_agentic_audit" tooldescription="Run an SEO, AI crawler and agentic browsing audit for a public URL.">
        <label>
          <span>URL to audit</span>
          <input id="audit-url" name="url" type="text" inputmode="url" autocomplete="url" autocapitalize="none" spellcheck="false" placeholder="example.com or https://example.com/page" required>
        </label>
        <label>
          <span>Target query</span>
          <input id="audit-query" name="query" type="text" placeholder="optional, e.g. AI SEO consultant">
        </label>
        <label>
          <span>Market</span>
          <input id="audit-market" name="market" type="text" value="United Kingdom">
        </label>
        <button id="audit-submit" type="submit">Run live audit</button>
      </form>
      <div class="example-row" aria-label="Example audits">
        <button type="button" data-audit-url="https://seo.copecheck.com/tool/" data-audit-query="seo audit checker" data-audit-market="United Kingdom">Audit this tool</button>
        <button type="button" data-audit-url="https://thesis.copecheck.com/" data-audit-query="AI discontinuity thesis" data-audit-market="United Kingdom">Audit thesis</button>
        <button type="button" data-audit-url="https://capabilities.copecheck.com/" data-audit-query="AI capability tracker" data-audit-market="United Kingdom">Audit capabilities</button>
      </div>
    </section>
    <section class="quality audit-positioning">
      <div class="section-head">
        <div>
          <h2>What the checker tests</h2>
          <p>It is not a generic score widget. The useful edge is checking whether a page can be crawled by both classic search engines and the AI systems people increasingly use as discovery layers.</p>
        </div>
      </div>
      <ul class="gate-list">
        <li><strong>Indexability</strong><span>HTTP status, robots, noindex, canonical and sitemap signals.</span></li>
        <li><strong>Organic traffic outlook</strong><span>A conservative forecast for how much open-web organic traffic the page is likely to win after ads, AI summaries and weak brand demand take their cut.</span></li>
        <li><strong>Google AI Search readiness</strong><span>Snippet eligibility, non-commodity content signals, query fan-out coverage and browser-agent structure.</span></li>
        <li><strong>Agentic browsing readiness</strong><span>Chrome Lighthouse-style checks for llms.txt fetch behaviour, static WebMCP hints, accessibility-tree basics and layout-stability follow-up.</span></li>
        <li><strong>AI crawl access</strong><span>GPTBot, OAI-SearchBot, ClaudeBot, PerplexityBot, Cloudflare edge robots and content-signal policy checks.</span></li>
        <li><strong>On-page quality</strong><span>Titles, descriptions, headings, crawlable text, alt text, schema and previews.</span></li>
        <li><strong>Competitor pull-in</strong><span>Search results are pulled for the target query, then MiniMax turns the audit into practical fixes where configured.</span></li>
      </ul>
    </section>
    <div id="audit-result"></div>
  </main>
  {script}
"""
    return render_layout("/tool/", "Free SEO and AI Crawl Checker", SEO_PAGES[6]["description"], body, snapshot)


def render_google_ai_search(snapshot: dict[str, Any]) -> str:
    body = f"""
  <main>
    <section class="page-hero">
      <p class="eyebrow">Google Search Central, applied</p>
      <h1>Google AI Search readiness</h1>
      <p class="lead">Google's AI Overviews and AI Mode still start with normal Search systems: crawlability, indexing, quality and snippets. The SEO checker turns that into practical checks instead of dressing old myths up as GEO.</p>
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>What changed in the checker</h2>
          <p>The tool now has a dedicated readiness layer for Google's generative AI features, built around the official guidance published by Google Search Central.</p>
        </div>
        <div class="section-actions">
          <a href="{escape(GOOGLE_AI_GUIDE_URL)}">Google source</a>
          <a href="/tool/">Run the checker</a>
        </div>
      </div>
      <ul class="gate-list">
        <li><strong>Eligibility first</strong><span>The page must return successfully, allow Googlebot, avoid noindex and remain eligible for snippets before Google AI features can use it.</span></li>
        <li><strong>Query fan-out coverage</strong><span>The checker generates adjacent intents from the target query so the page can answer the related questions Google may retrieve for grounding.</span></li>
        <li><strong>Non-commodity content</strong><span>The audit looks for evidence, named examples, methodology, first-hand detail, dates and a clear point of view rather than generic filler.</span></li>
        <li><strong>Agentic UX</strong><span>Semantic landmarks, labelled controls and readable page structure help browser agents and assistive technology interpret the page.</span></li>
        <li><strong>Lighthouse agentic browsing</strong><span>The checker now separates Search visibility from agent readiness: llms.txt is optional for Google Search, but useful to monitor because Chrome Lighthouse checks its fetch behaviour for browser agents.</span></li>
        <li><strong>WebMCP hints</strong><span>Action-heavy pages are checked for static WebMCP-style form tool names and descriptions, with a link to validate richer dynamic registration in Lighthouse.</span></li>
      </ul>
    </section>
    <section class="quality-detail">
      <article>
        <h2>Useful tools to add next</h2>
        <p><strong>Search Console importer:</strong> pull queries, pages, clicks and impressions into the public dashboard so AI Search changes can be correlated with real visibility.</p>
        <p><strong>Fan-out gap tracker:</strong> store generated fan-out prompts per audited URL and mark which ones are answered on-page after edits.</p>
        <p><strong>Agentic browsing report:</strong> run Lighthouse after the server-side audit to verify WebMCP registration, accessibility tree quality, cumulative layout shift and llms.txt behaviour in Chrome.</p>
        <p><strong>Commodity risk queue:</strong> flag pages that look like generic guides and push them into a rewrite queue with required evidence fields.</p>
        <p><strong>PageSpeed Insights hook:</strong> call PSI after crawl blockers are fixed and show Core Web Vitals beside the readiness score.</p>
      </article>
      <article>
        <h2>What not to sell as magic</h2>
        <p>Google says there is no special markup or llms.txt requirement for generative AI features in Search. Chrome Lighthouse now treats llms.txt as an optional agent-discovery surface, so the honest position is simple: it is useful infrastructure for agents, not a ranking lever.</p>
        <p>The same applies to chunking, fake mentions and schema overuse. The cleaner pitch is better: build useful, source-backed, crawlable pages that people would actually want to read.</p>
      </article>
      <article>
        <h2>How this helps CopeCheck</h2>
        <p>CopeCheck has a natural advantage because the useful pages are sourced records with verdicts, links and a point of view. The risk is thin repetition. The readiness layer is designed to keep the network on the programmatic side of the line, not the scaled-content-abuse side.</p>
      </article>
      <article>
        <h2>Marketable product angle</h2>
        <p>This can be sold as a Google AI Search readiness check: not a promise of AI Overview placement, but a practical audit of whether a page is discoverable, snippet-eligible, useful, structured and competitive enough to be retrieved.</p>
      </article>
    </section>
    {render_sources()}
  </main>
"""
    return render_layout("/google-ai-search/", "Google AI Search Readiness", SEO_PAGES[7]["description"], body, snapshot)


def render_updates(snapshot: dict[str, Any]) -> str:
    update_cards = "\n".join(
        f"""
        <article>
          <time datetime="{escape(update["date"])}">{escape(update["date"])}</time>
          <h2>{escape(update["title"])}</h2>
          <p>{escape(update["summary"])}</p>
          <a href="{escape(update["url"])}">Open related page</a>
        </article>
        """
        for update in SEO_UPDATES
    )
    body = f"""
  <main>
    <section class="page-hero">
      <h1>CopeCheck SEO updates</h1>
      <p class="lead">A crawlable build log for the public SEO Lab: what changed, why it matters, and where the improvement lives.</p>
    </section>
    <section class="update-list">
      {update_cards}
    </section>
    <section class="quality">
      <div class="section-head">
        <div>
          <h2>What gets logged here</h2>
          <p>This page turns product improvements into visible crawlable evidence instead of burying the work in server notes.</p>
        </div>
      </div>
      <ul class="gate-list">
        <li><strong>Scoring changes</strong><span>New audit checks, robots handling, AI crawler policy and quality gates.</span></li>
        <li><strong>Discovery changes</strong><span>Sitemap, RSS, llms.txt, schema and internal-linking improvements.</span></li>
        <li><strong>Feedback loops</strong><span>Visitor feedback, shipped suggestions and checks that were rejected for good reasons.</span></li>
        <li><strong>Search evidence</strong><span>Search Console and Bing visibility changes once the public export shows movement.</span></li>
      </ul>
    </section>
  </main>
"""
    return render_layout("/updates/", "CopeCheck SEO Updates", SEO_PAGES[8]["description"], body, snapshot)


def render_sitemap() -> bytes:
    lastmod = datetime.now(timezone.utc).date().isoformat()
    urls = "\n".join(
        f"""  <url>
    <loc>{escape(PUBLIC_BASE + page["path"])}</loc>
    <lastmod>{lastmod}</lastmod>
  </url>"""
        for page in SEO_PAGES
    )
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{urls}
</urlset>
""".encode("utf-8")


def render_feed(snapshot: dict[str, Any]) -> bytes:
    updated = datetime.now(timezone.utc)
    page_items = "\n".join(
        f"""
    <item>
      <title>{escape(update["title"])}</title>
      <link>{escape(PUBLIC_BASE + update["url"])}</link>
      <guid>{escape(PUBLIC_BASE + "/updates/#" + re.sub(r"[^a-z0-9]+", "-", update["title"].lower()).strip("-"))}</guid>
      <pubDate>{escape(format_datetime(datetime.fromisoformat(update["date"]).replace(tzinfo=timezone.utc), usegmt=True))}</pubDate>
      <description>{escape(update["summary"] + " " + AI_DISCLOSURE_TEXT)}</description>
    </item>"""
        for update in SEO_UPDATES
    )
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
  <channel>
    <title>CopeCheck SEO updates</title>
    <link>{escape(PUBLIC_BASE + "/updates/")}</link>
    <description>Public changelog for CopeCheck SEO, crawl, AI crawler and sitemap work.</description>
    <language>en-gb</language>
    <lastBuildDate>{escape(format_datetime(updated, usegmt=True))}</lastBuildDate>
{page_items}
  </channel>
</rss>
""".encode("utf-8")


def render_llms(snapshot: dict[str, Any]) -> bytes:
    totals = snapshot.get("totals") if isinstance(snapshot.get("totals"), dict) else {}
    pages = "\n".join(
        f"- {page['title']}: {PUBLIC_BASE}{page['path']} - {page['description']}"
        for page in SEO_PAGES
    )
    updates = "\n".join(
        f"- {update['date']}: {update['title']} - {update['summary']}"
        for update in SEO_UPDATES[:8]
    )
    text = f"""# CopeCheck SEO Lab

Purpose: public SEO, AI crawler and search visibility lab for the CopeCheck network.

Canonical site: {PUBLIC_BASE}/
Machine data: {PUBLIC_BASE}/data.json
Sitemap: {PUBLIC_BASE}/sitemap.xml
RSS updates: {PUBLIC_BASE}/feed.xml
Audit tool: {PUBLIC_BASE}/tool/

Current public totals:
- Live hosts: {totals.get("sites_live", 0)}/{totals.get("sites", 0)}
- Sitemap URLs: {totals.get("sitemap_urls", 0)}
- Oracle entries: {totals.get("oracle_entries", 0)}

Important pages:
{pages}

Recent updates:
{updates}

Notes for agents:
- The audit tool checks public robots.txt, sitemap.xml, llms.txt, canonical/meta signals, Google AI Search readiness, Chrome Lighthouse-style agentic browsing readiness, AI crawler policy, Cloudflare edge robots/content-signal behaviour and competitor SERP gaps.
- llms.txt is offered for agent convenience only. Google's AI Search guidance does not require special AI markup or llms.txt, while Chrome Lighthouse's agentic browsing docs now treat llms.txt fetch behaviour as an optional readiness signal for agents.
- Static WebMCP hints are detected from form tool names/descriptions; dynamic WebMCP registration should still be validated in Chrome Lighthouse.
- Cloudflare edge robots responses are treated as the public source of truth because crawlers see the edge, not the origin's private intent.
- Search Console credentials are not exposed here. The public dashboard reads sanitized snapshots only.
"""
    return text.encode("utf-8")


def render_robots() -> bytes:
    return f"""User-agent: *
Allow: /

Sitemap: {PUBLIC_BASE}/sitemap.xml
""".encode("utf-8")


def render_favicon() -> bytes:
    return b"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
  <rect width="64" height="64" rx="12" fill="#111827"/>
  <text x="32" y="39" text-anchor="middle" font-family="Arial, sans-serif" font-size="18" font-weight="800" fill="#ffffff">CC</text>
</svg>
"""


AI_DISCLOSURE_TEXT = "AI-generated analytical output; verify against linked sources. Model outputs may contain errors."


def ai_disclosure_page() -> bytes:
    return b'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>AI Disclosure | CopeCheck SEO</title></head><body><main><article style="max-width:52rem;margin:3rem auto;line-height:1.65"><h1>How CopeCheck SEO uses AI</h1><p><strong>Some audit explanations, summaries and network commentary may be generated by artificial intelligence.</strong> Technical measurements such as HTTP responses, indexability checks and sitemap status are collected deterministically.</p><h2>Models and method</h2><p>The CopeCheck network uses OpenAI Codex/GPT-family models, currently gpt-5.6-luna with maximum reasoning for the main scoring path, and MiniMax models for specialist and fallback pipelines. SEO outputs combine deterministic page checks with model-assisted interpretation.</p><h2>Limits and corrections</h2><p>Generated text may contain errors. Verify recommendations against the measured fields and linked primary documentation. Send the page URL and evidence to <a href="mailto:btl101@gmail.com?subject=CopeCheck%20SEO%20correction">btl101@gmail.com</a>.</p></article></main><footer></footer></body></html>'''


def inject_ai_disclosure(body: bytes, content_type: str) -> bytes:
    if not content_type.startswith("text/html"):
        return body
    text = body.decode("utf-8", errors="replace")
    if "cc-ai-label" in text:
        return body
    label = '''<style>.cc-ai-label,.cc-ai-footer{box-sizing:border-box;border:1px solid rgba(245,158,11,.45);border-radius:.65rem;background:rgba(245,158,11,.08);color:inherit;padding:.75rem 1rem;line-height:1.5}.cc-ai-label{margin:1rem auto;max-width:72rem}.cc-ai-label strong{margin-right:.4rem;text-transform:uppercase;letter-spacing:.04em}.cc-ai-label a,.cc-ai-footer a{color:inherit;text-decoration:underline}.cc-ai-footer{margin:1rem 0;font-size:.85rem}</style><aside class="cc-ai-label" role="note"><strong>AI-assisted analysis</strong> Some summaries may be AI-generated; measured SEO fields are deterministic. <a href="/ai-disclosure">How CopeCheck uses AI</a>.</aside>'''
    footer = '''<p class="cc-ai-footer"><strong>AI disclosure:</strong> Some analytical summaries may be AI-generated and may contain errors. <a href="/ai-disclosure">Full disclosure</a>.</p>'''
    main_at = text.find("<main")
    if main_at >= 0:
        main_end = text.find(">", main_at)
        if main_end >= 0:
            text = text[:main_end + 1] + label + text[main_end + 1:]
    footer_at = text.find("<footer")
    if footer_at >= 0:
        footer_end = text.find(">", footer_at)
        text = text[:footer_end + 1] + footer + text[footer_end + 1:]
    else:
        text = text.replace("</body>", f"<footer>{footer}</footer></body>", 1)
    return text.encode("utf-8")


class Handler(BaseHTTPRequestHandler):
    server_version = "CopeCheckSEO/1.0"

    def log_message(self, fmt: str, *args: Any) -> None:
        return

    def send_security_headers(self) -> None:
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("X-Frame-Options", "DENY")
        self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
        self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=(), interest-cohort=()")

    def send_bytes(self, status: int, body: bytes, content_type: str, head_only: bool = False) -> None:
        body = inject_ai_disclosure(body, content_type)
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Cache-Control", "public, max-age=300, stale-while-revalidate=900")
        self.send_header("Content-Length", str(len(body)))
        self.send_security_headers()
        self.end_headers()
        if not head_only:
            try:
                self.wfile.write(body)
            except (BrokenPipeError, ConnectionResetError):
                return

    def send_html(self, status: int, body: str, head_only: bool = False) -> None:
        self.send_bytes(status, body.encode("utf-8"), "text/html; charset=utf-8", head_only=head_only)

    def send_json(self, status: int, payload: dict[str, Any], head_only: bool = False) -> None:
        body = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(body)))
        self.send_security_headers()
        self.end_headers()
        if not head_only:
            self.wfile.write(body)

    def do_HEAD(self) -> None:
        self.handle_request(head_only=True)

    def do_GET(self) -> None:
        self.handle_request(head_only=False)

    def do_POST(self) -> None:
        path = urlparse(self.path).path
        if path == "/api/audit":
            self.handle_audit_api(head_only=False)
            return
        if path == "/api/feedback":
            self.handle_feedback_api(head_only=False)
            return
        self.send_json(405, {"ok": False, "error": "Method not allowed."})

    def client_identifier(self) -> str:
        return (
            self.headers.get("CF-Connecting-IP")
            or self.headers.get("X-Forwarded-For", "").split(",", 1)[0].strip()
            or self.client_address[0]
        )

    def audit_payload(self) -> dict[str, str]:
        if self.command == "GET":
            params = parse_qs(urlparse(self.path).query)
            return {key: values[0] for key, values in params.items() if values}
        content_length = int(self.headers.get("Content-Length") or "0")
        if content_length > AUDIT_BODY_LIMIT:
            raise ValueError("Request body is too large.")
        raw = self.rfile.read(content_length) if content_length else b"{}"
        content_type = self.headers.get("Content-Type", "")
        if "application/json" in content_type:
            data = json.loads(raw.decode("utf-8", errors="ignore") or "{}")
            if not isinstance(data, dict):
                raise ValueError("JSON body must be an object.")
            return {str(key): str(value) for key, value in data.items()}
        params = parse_qs(raw.decode("utf-8", errors="ignore"))
        return {key: values[0] for key, values in params.items() if values}

    def feedback_payload(self) -> dict[str, Any]:
        content_length = int(self.headers.get("Content-Length") or "0")
        if content_length > FEEDBACK_BODY_LIMIT:
            raise ValueError("Request body is too large.")
        raw = self.rfile.read(content_length) if content_length else b"{}"
        content_type = self.headers.get("Content-Type", "")
        if "application/json" in content_type:
            data = json.loads(raw.decode("utf-8", errors="ignore") or "{}")
            if not isinstance(data, dict):
                raise ValueError("JSON body must be an object.")
            return data
        params = parse_qs(raw.decode("utf-8", errors="ignore"))
        return {key: values[0] for key, values in params.items() if values}

    def handle_audit_api(self, head_only: bool = False) -> None:
        allowed, remaining = rate_limit_ok(self.client_identifier())
        if not allowed:
            self.send_json(
                429,
                {
                    "ok": False,
                    "error": f"Rate limit reached. Try again later. Limit is {AUDIT_RATE_LIMIT} audits per hour.",
                },
                head_only=head_only,
            )
            return
        try:
            payload = self.audit_payload()
            audit = run_seo_audit(
                payload.get("url", ""),
                query=payload.get("query", ""),
                market=payload.get("market", "United Kingdom") or "United Kingdom",
            )
        except ValueError as exc:
            self.send_json(400, {"ok": False, "error": str(exc)}, head_only=head_only)
            return
        except json.JSONDecodeError:
            self.send_json(400, {"ok": False, "error": "Could not parse JSON request body."}, head_only=head_only)
            return
        except Exception as exc:
            self.send_json(502, {"ok": False, "error": f"Audit failed: {exc}"}, head_only=head_only)
            return
        self.send_json(200, {"ok": True, "remaining": remaining, "audit": audit}, head_only=head_only)

    def handle_feedback_api(self, head_only: bool = False) -> None:
        allowed, remaining = feedback_rate_limit_ok(self.client_identifier())
        if not allowed:
            self.send_json(
                429,
                {
                    "ok": False,
                    "error": f"Rate limit reached. Try again later. Limit is {FEEDBACK_RATE_LIMIT} feedback submissions per hour.",
                },
                head_only=head_only,
            )
            return
        try:
            payload = self.feedback_payload()
            feedback = save_feedback(payload, self.client_identifier(), self.headers.get("User-Agent", ""))
        except ValueError as exc:
            self.send_json(400, {"ok": False, "error": str(exc)}, head_only=head_only)
            return
        except json.JSONDecodeError:
            self.send_json(400, {"ok": False, "error": "Could not parse JSON request body."}, head_only=head_only)
            return
        except Exception as exc:
            self.send_json(502, {"ok": False, "error": f"Feedback failed: {exc}"}, head_only=head_only)
            return
        self.send_json(200, {"ok": True, "remaining": remaining, "feedback": feedback}, head_only=head_only)

    def handle_request(self, head_only: bool = False) -> None:
        path = urlparse(self.path).path
        # --- cc_canonical_slash_guard (added 20260926T082053Z by infra health sweep) ---
        # SEO_PAGES are published with a trailing slash; the unslashed form
        # used to 404. Redirect it to the canonical form instead of dead-ending.
        if self.command in ("GET", "HEAD") and len(path) > 1:
            _cc_canonical = {p["path"] for p in SEO_PAGES if p.get("path", "").endswith("/")}
            _cc_canonical.discard("/")
            _cc_alt = path.rstrip("/") if path.endswith("/") else path + "/"
            if path not in _cc_canonical and _cc_alt in _cc_canonical:
                _cc_target = _cc_alt
                _cc_query = urlparse(self.path).query
                if _cc_query:
                    _cc_target += "?" + _cc_query
                self.send_response(301)
                self.send_header("Location", _cc_target)
                self.send_header("Content-Length", "0")
                self.send_security_headers()
                self.end_headers()
                return
        # --- end cc_canonical_slash_guard ---
        archive_files = {
            "/search-progress/archive-2026-may-august/": ("index.html", "text/html; charset=utf-8"),
            "/search-progress/archive-2026-may-august/monthly-search.csv": ("monthly-search.csv", "text/csv; charset=utf-8"),
            "/search-progress/archive-2026-may-august/08-search-decline-full-august.svg": ("08-search-decline-full-august.svg", "image/svg+xml"),
        }
        if path in archive_files:
            filename, content_type = archive_files[path]
            self.send_bytes(200, (DATA_DIR / "conference-archive" / filename).read_bytes(), content_type, head_only=head_only)
            return
        if path == "/api/audit":
            self.handle_audit_api(head_only=head_only)
            return
        if path == "/api/feedback":
            self.handle_feedback_api(head_only=head_only)
            return
        if path == "/healthz":
            self.send_bytes(200, b"ok\n", "text/plain; charset=utf-8", head_only=head_only)
            return
        if path in {"/ai-disclosure", "/ai-disclosure/"}:
            self.send_bytes(200, ai_disclosure_page(), "text/html; charset=utf-8", head_only=head_only)
            return
        if path == "/robots.txt":
            self.send_bytes(200, render_robots(), "text/plain; charset=utf-8", head_only=head_only)
            return
        if path == "/favicon.ico":
            self.send_bytes(200, render_favicon(), "image/svg+xml", head_only=head_only)
            return
        if path == "/sitemap.xml":
            self.send_bytes(200, render_sitemap(), "application/xml; charset=utf-8", head_only=head_only)
            return
        if path == "/feed.xml":
            self.send_bytes(200, render_feed(get_layout_snapshot()), "application/rss+xml; charset=utf-8", head_only=head_only)
            return
        if path == "/llms.txt":
            self.send_bytes(200, render_llms(get_layout_snapshot()), "text/plain; charset=utf-8", head_only=head_only)
            return
        if path == "/tool/":
            self.send_html(200, render_audit_tool(get_layout_snapshot()), head_only=head_only)
            return
        snapshot = get_snapshot(force="refresh=1" in self.path)
        if path == "/data.json":
            body = json.dumps(snapshot, ensure_ascii=False, indent=2).encode("utf-8")
            self.send_bytes(200, body, "application/json; charset=utf-8", head_only=head_only)
            return
        if path == "/":
            self.send_html(200, render_home(snapshot), head_only=head_only)
            return
        if path == "/rationale/":
            self.send_html(200, render_rationale(snapshot), head_only=head_only)
            return
        if path == "/subdomains/":
            self.send_html(200, render_subdomains(snapshot), head_only=head_only)
            return
        if path == "/quality-system/":
            self.send_html(200, render_quality_system(snapshot), head_only=head_only)
            return
        if path == "/search-progress/":
            self.send_html(200, render_search_progress(snapshot), head_only=head_only)
            return
        if path == "/search-console-api/":
            self.send_html(200, render_search_console_api(snapshot), head_only=head_only)
            return
        if path == "/google-ai-search/":
            self.send_html(200, render_google_ai_search(snapshot), head_only=head_only)
            return
        if path == "/updates/":
            self.send_html(200, render_updates(snapshot), head_only=head_only)
            return
        self.send_html(404, render_layout(path, "Not found", "Page not found.", "<main><section class='page-hero'><h1>Not found</h1><p class='lead'>That SEO lab page does not exist.</p></section></main>", snapshot), head_only=head_only)


CSS = r"""
:root {
  color-scheme: light;
  --bg: #f7f8fb;
  --ink: #12151b;
  --muted: #5f6876;
  --panel: #ffffff;
  --line: #dce2ea;
  --dark: #111827;
  --green: #0f766e;
  --blue: #2563eb;
  --gold: #b45309;
  --rose: #be123c;
  --shadow: 0 22px 60px rgba(18, 21, 27, 0.11);
}
* {
  box-sizing: border-box;
}
body {
  margin: 0;
  background: var(--bg);
  color: var(--ink);
  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
  letter-spacing: 0;
}
a {
  color: inherit;
  text-decoration: none;
}
p {
  color: var(--muted);
  line-height: 1.68;
}
.topbar {
  position: sticky;
  top: 0;
  z-index: 5;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
  padding: 16px clamp(18px, 4vw, 54px);
  background: rgba(247, 248, 251, 0.9);
  border-bottom: 1px solid rgba(220, 226, 234, 0.9);
  backdrop-filter: blur(16px);
}
.brand {
  display: inline-flex;
  align-items: center;
  gap: 12px;
  min-width: max-content;
}
.brand-mark {
  display: grid;
  place-items: center;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: var(--dark);
  color: white;
  font-weight: 800;
  font-size: 13px;
}
.brand strong,
.brand small {
  display: block;
}
.brand small {
  color: var(--muted);
  font-size: 12px;
  margin-top: 1px;
}
nav {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}
nav a,
.top-action,
.button {
  border-radius: 8px;
  font-size: 14px;
  font-weight: 700;
}
nav a {
  padding: 9px 12px;
  color: var(--muted);
}
nav a.active,
nav a:hover {
  background: var(--panel);
  color: var(--ink);
  box-shadow: inset 0 0 0 1px var(--line);
}
.top-action {
  padding: 10px 14px;
  background: var(--ink);
  color: white;
  min-width: max-content;
}
main {
  width: min(1180px, calc(100% - 32px));
  margin: 0 auto;
}
.hero,
.page-hero {
  min-height: 520px;
  display: grid;
  align-items: center;
  gap: clamp(28px, 5vw, 72px);
  padding: clamp(56px, 9vw, 96px) 0 48px;
}
.hero {
  grid-template-columns: minmax(0, 1.1fr) minmax(320px, 0.72fr);
}
.page-hero {
  min-height: 330px;
  max-width: 880px;
}
h1 {
  margin: 0;
  max-width: 900px;
  font-size: clamp(48px, 7vw, 96px);
  line-height: 0.95;
  letter-spacing: 0;
}
.page-hero h1 {
  font-size: clamp(42px, 6vw, 82px);
}
h2 {
  margin: 0;
  font-size: clamp(27px, 4vw, 44px);
  line-height: 1.08;
  letter-spacing: 0;
}
h3 {
  margin: 0;
  font-size: 20px;
  line-height: 1.22;
}
.lead {
  max-width: 720px;
  font-size: 20px;
}
.hero-actions,
.section-head {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}
.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 44px;
  padding: 0 18px;
  border: 1px solid var(--line);
}
.button.primary {
  background: var(--ink);
  color: white;
  border-color: var(--ink);
}
.button.secondary {
  background: var(--panel);
  color: var(--ink);
}
.hero-panel {
  background: var(--dark);
  color: white;
  border-radius: 8px;
  padding: 28px;
  box-shadow: var(--shadow);
}
.panel-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding-bottom: 22px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.18);
}
.panel-header span,
.signal-stack span,
.metric span,
.metric em,
td small,
.oracle-card small {
  color: var(--muted);
  font-style: normal;
}
.hero-panel .panel-header span,
.hero-panel .signal-stack span {
  color: rgba(255, 255, 255, 0.64);
}
.panel-header strong {
  color: #7dd3fc;
  text-align: right;
}
.signal-stack {
  display: grid;
  gap: 14px;
  margin-top: 22px;
}
.signal-stack div {
  display: flex;
  justify-content: space-between;
  gap: 18px;
}
.metrics {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px;
  margin-bottom: 42px;
}
.metric {
  display: grid;
  gap: 8px;
  min-height: 150px;
  padding: 20px;
  background: var(--panel);
  border: 1px solid var(--line);
  border-top: 4px solid var(--ink);
  border-radius: 8px;
  box-shadow: 0 10px 28px rgba(18, 21, 27, 0.05);
}
.metric.green { border-top-color: var(--green); }
.metric.blue { border-top-color: var(--blue); }
.metric.gold { border-top-color: var(--gold); }
.metric.rose { border-top-color: var(--rose); }
.metric strong {
  font-size: 42px;
  line-height: 1;
}
.network-table,
.dashboard-analytics,
.quality,
.sources,
.copy-band,
.quality-detail {
  margin: 42px 0;
  padding: clamp(22px, 4vw, 36px);
  background: var(--panel);
  border: 1px solid var(--line);
  border-radius: 8px;
  box-shadow: 0 12px 40px rgba(18, 21, 27, 0.05);
}
.section-head {
  justify-content: space-between;
  margin-bottom: 22px;
}
.section-head p,
.section-copy {
  max-width: 720px;
  margin-bottom: 0;
}
.section-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: flex-end;
}
.section-actions a {
  display: inline-flex;
  align-items: center;
  min-height: 38px;
  padding: 0 12px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
  color: var(--blue);
  font-size: 13px;
  font-weight: 800;
}
.section-actions a:hover {
  border-color: #9db7d8;
}
.analytics-kpis {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}
.analytics-kpis div {
  display: grid;
  gap: 6px;
  min-height: 112px;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
}
.analytics-kpis span,
.analytics-split li span {
  color: var(--muted);
  font-size: 14px;
}
.analytics-kpis strong {
  color: var(--ink);
  font-size: clamp(30px, 4vw, 46px);
  line-height: 1;
}
.analytics-split {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
}
.analytics-split article {
  padding: 20px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #ffffff;
}
.analytics-split h3 {
  margin: 0 0 14px;
  font-size: 21px;
}
.analytics-split ul {
  display: grid;
  gap: 10px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.analytics-split li {
  display: grid;
  gap: 4px;
  padding-top: 10px;
  border-top: 1px solid #e8eef6;
}
.analytics-split li:first-child {
  padding-top: 0;
  border-top: 0;
}
.analytics-split li strong {
  overflow-wrap: anywhere;
}
.table-wrap {
  overflow-x: auto;
}
table {
  width: 100%;
  border-collapse: collapse;
  min-width: 780px;
}
th,
td {
  padding: 15px 12px;
  text-align: left;
  border-bottom: 1px solid var(--line);
  vertical-align: top;
  font-size: 14px;
}
th {
  color: var(--muted);
  font-size: 12px;
  text-transform: uppercase;
}
.host-link {
  display: block;
  color: var(--blue);
  font-weight: 800;
}
td small {
  display: block;
  margin-top: 4px;
}
.chip {
  display: inline-flex;
  align-items: center;
  min-height: 26px;
  padding: 0 9px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 800;
  background: #eef2f7;
  color: var(--muted);
  white-space: nowrap;
}
.chip.ok {
  background: #dff8ee;
  color: #066148;
}
.chip.warn {
  background: #ffe8e8;
  color: #9f1239;
}
.split {
  display: grid;
  grid-template-columns: minmax(260px, 0.34fr) minmax(0, 1fr);
  gap: 28px;
  margin: 64px 0;
}
.oracle-grid,
.lane-grid,
.quality-detail {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 14px;
}
.oracle-card a,
.lane-grid article,
.quality-detail article {
  display: grid;
  gap: 11px;
  min-height: 190px;
  padding: 20px;
  background: var(--panel);
  border: 1px solid var(--line);
  border-radius: 8px;
}
.oracle-card a:hover,
.lane-grid article:hover {
  border-color: #9db7d8;
  transform: translateY(-1px);
}
.score {
  display: grid;
  place-items: center;
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: var(--ink);
  color: white;
  font-weight: 900;
}
.oracle-card p {
  margin: 0;
  font-size: 14px;
}
.gate-list {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 14px;
  padding: 0;
  margin: 0;
  list-style: none;
}
.gate-list li {
  display: grid;
  gap: 10px;
  min-height: 148px;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
}
.gate-list span {
  color: var(--muted);
  line-height: 1.55;
  font-size: 14px;
}
.flow-list {
  display: grid;
  grid-template-columns: repeat(5, minmax(0, 1fr));
  gap: 12px;
  padding: 0;
  margin: 0;
  list-style: none;
  counter-reset: flow;
}
.flow-list li {
  position: relative;
  display: grid;
  align-content: start;
  gap: 10px;
  min-height: 170px;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
  counter-increment: flow;
}
.flow-list li::before {
  content: counter(flow, decimal-leading-zero);
  display: grid;
  place-items: center;
  width: 34px;
  height: 28px;
  border-radius: 8px;
  background: #e8f2ff;
  color: var(--blue);
  font-size: 12px;
  font-weight: 900;
}
.flow-list span {
  color: var(--muted);
  font-size: 14px;
  line-height: 1.55;
}
.copy-band {
  max-width: 900px;
}
.sources div,
.footer-links {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}
.related-shell {
  display: grid;
  grid-template-columns: minmax(260px, 0.34fr) minmax(0, 1fr);
  gap: 24px;
  width: min(1180px, calc(100% - 32px));
  margin: 64px auto 42px;
  padding-top: 34px;
  border-top: 1px solid var(--line);
}
.related-shell h2 {
  font-size: clamp(26px, 3vw, 38px);
}
.related-shell small {
  display: block;
  margin-top: 12px;
  color: var(--muted);
}
.related-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}
.related-grid a {
  display: grid;
  gap: 8px;
  min-height: 132px;
  padding: 18px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  box-shadow: 0 10px 30px rgba(18, 21, 27, 0.045);
}
.related-grid a:hover {
  border-color: #9db7d8;
  transform: translateY(-1px);
}
.related-grid span {
  color: var(--muted);
  font-size: 14px;
  line-height: 1.5;
}
.sources a,
.footer-links a {
  padding: 8px 10px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
  color: var(--blue);
  font-size: 13px;
  font-weight: 700;
}
.sources.warning {
  border-color: rgba(190, 18, 60, 0.25);
  background: #fff9f9;
}
.sources.warning h2 {
  color: var(--rose);
}
.update-list {
  display: grid;
  gap: 14px;
  margin: 0 0 48px;
}
.update-list article {
  display: grid;
  gap: 10px;
  padding: clamp(20px, 4vw, 30px);
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  box-shadow: 0 12px 34px rgba(18, 21, 27, 0.045);
}
.update-list time {
  color: var(--blue);
  font-size: 13px;
  font-weight: 900;
  text-transform: uppercase;
}
.update-list h2 {
  font-size: clamp(24px, 3vw, 36px);
}
.update-list a {
  color: var(--blue);
  font-weight: 900;
}
.trend-panel {
  overflow: hidden;
}
.trend-controls,
.trend-readout,
.trend-axis,
.trend-legend {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}
.trend-controls {
  align-items: flex-end;
  margin-bottom: 16px;
}
.trend-controls label {
  display: grid;
  gap: 6px;
  min-width: 154px;
  color: var(--muted);
  font-size: 12px;
  font-weight: 800;
  text-transform: uppercase;
}
.trend-controls input {
  min-height: 42px;
  padding: 0 11px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
  color: var(--ink);
  font: inherit;
  font-size: 14px;
  font-weight: 700;
}
.trend-presets {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.trend-presets button {
  min-height: 42px;
  padding: 0 12px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  color: var(--ink);
  font: inherit;
  font-size: 13px;
  font-weight: 800;
  cursor: pointer;
}
.trend-presets button:hover,
.trend-controls input:focus-visible {
  border-color: #9db7d8;
  outline: 2px solid rgba(37, 99, 235, 0.14);
  outline-offset: 2px;
}
.trend-readout {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  margin: 12px 0 18px;
}
.trend-readout div {
  display: grid;
  gap: 5px;
  min-height: 78px;
  padding: 14px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
}
.trend-readout span,
.trend-axis,
.trend-legend {
  color: var(--muted);
  font-size: 13px;
  font-weight: 700;
}
.trend-readout strong {
  font-size: 26px;
  line-height: 1;
}
.trend-chart-wrap {
  height: clamp(240px, 34vw, 360px);
  padding: 16px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: linear-gradient(180deg, #fbfcfe, #ffffff);
}
.trend-chart {
  display: block;
  width: 100%;
  height: 100%;
}
.trend-grid {
  stroke: #e7edf5;
  stroke-width: 1;
}
.trend-bar {
  fill: rgba(37, 99, 235, 0.38);
}
.trend-line {
  fill: none;
  stroke: var(--green);
  stroke-width: 4;
  stroke-linecap: round;
  stroke-linejoin: round;
  vector-effect: non-scaling-stroke;
}
.trend-dot {
  fill: var(--panel);
  stroke: var(--green);
  stroke-width: 3;
  vector-effect: non-scaling-stroke;
}
.trend-axis {
  justify-content: space-between;
  margin-top: 10px;
}
.trend-legend {
  align-items: center;
  margin-top: 12px;
}
.trend-legend span {
  display: inline-flex;
  align-items: center;
  gap: 7px;
}
.trend-legend i {
  display: inline-block;
  width: 22px;
  height: 4px;
  border-radius: 999px;
}
.legend-bar {
  background: rgba(37, 99, 235, 0.38);
}
.legend-line {
  background: var(--green);
}
.feedback-launch {
  position: fixed;
  right: 18px;
  bottom: 18px;
  z-index: 20;
  min-height: 44px;
  padding: 0 16px;
  border: 0;
  border-radius: 999px;
  background: var(--ink);
  color: white;
  box-shadow: 0 12px 34px rgba(18, 21, 27, 0.22);
  font: inherit;
  font-size: 14px;
  font-weight: 900;
  cursor: pointer;
}
.feedback-modal[hidden] {
  display: none;
}
.feedback-modal {
  position: fixed;
  inset: 0;
  z-index: 30;
  display: grid;
  place-items: end center;
  padding: 18px;
}
.feedback-backdrop {
  position: absolute;
  inset: 0;
  border: 0;
  background: rgba(17, 24, 39, 0.44);
  cursor: pointer;
}
.feedback-dialog {
  position: relative;
  z-index: 1;
  display: grid;
  gap: 14px;
  width: min(560px, 100%);
  padding: 20px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  box-shadow: var(--shadow);
}
.feedback-head {
  display: flex;
  justify-content: space-between;
  gap: 14px;
  align-items: start;
}
.feedback-head strong,
.feedback-head span {
  display: block;
}
.feedback-head strong {
  font-size: 20px;
}
.feedback-head span,
.feedback-dialog label span,
.feedback-actions span {
  color: var(--muted);
  font-size: 13px;
}
.feedback-head button {
  min-height: 34px;
  padding: 0 10px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
  color: var(--ink);
  font: inherit;
  font-size: 13px;
  font-weight: 800;
  cursor: pointer;
}
.feedback-dialog label {
  display: grid;
  gap: 6px;
  font-weight: 800;
}
.feedback-dialog select,
.feedback-dialog textarea,
.feedback-dialog input {
  width: 100%;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
  color: var(--ink);
  font: inherit;
}
.feedback-dialog select,
.feedback-dialog input {
  min-height: 42px;
  padding: 0 11px;
}
.feedback-dialog textarea {
  min-height: 132px;
  resize: vertical;
  padding: 11px;
}
.feedback-dialog select:focus-visible,
.feedback-dialog textarea:focus-visible,
.feedback-dialog input:focus-visible {
  outline: 2px solid rgba(37, 99, 235, 0.18);
  outline-offset: 2px;
  border-color: #9db7d8;
}
.feedback-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}
.feedback-actions button {
  min-height: 42px;
  padding: 0 14px;
  border: 0;
  border-radius: 8px;
  background: var(--ink);
  color: white;
  font: inherit;
  font-size: 14px;
  font-weight: 900;
  cursor: pointer;
}
.feedback-actions button:disabled {
  cursor: progress;
  opacity: 0.72;
}
.has-feedback-modal {
  overflow: hidden;
}
.eyebrow {
  margin: 0 0 14px;
  color: var(--blue);
  font-size: 13px;
  font-weight: 900;
  letter-spacing: 0;
  text-transform: uppercase;
}
.tool-hero {
  min-height: 380px;
}
.audit-tool {
  margin: 0 0 42px;
  padding: clamp(20px, 4vw, 30px);
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--dark);
  color: white;
  box-shadow: var(--shadow);
}
.audit-form {
  display: grid;
  grid-template-columns: minmax(260px, 1.35fr) minmax(190px, 0.9fr) minmax(150px, 0.62fr) auto;
  gap: 12px;
  align-items: end;
}
.audit-form label {
  display: grid;
  gap: 7px;
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
  font-weight: 900;
  text-transform: uppercase;
}
.audit-form input {
  min-height: 48px;
  width: 100%;
  padding: 0 13px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.08);
  color: white;
  font: inherit;
  font-size: 15px;
  font-weight: 700;
}
.audit-form input::placeholder {
  color: rgba(255, 255, 255, 0.48);
}
.audit-form input:focus-visible {
  outline: 2px solid rgba(125, 211, 252, 0.55);
  outline-offset: 2px;
}
.audit-form button,
.example-row button {
  min-height: 48px;
  border: 0;
  border-radius: 8px;
  font: inherit;
  font-size: 14px;
  font-weight: 900;
  cursor: pointer;
}
.audit-form button {
  padding: 0 18px;
  background: #7dd3fc;
  color: #082f49;
  white-space: nowrap;
}
.audit-form button:disabled {
  cursor: progress;
  opacity: 0.72;
}
.example-row {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 14px;
}
.example-row button {
  min-height: 36px;
  padding: 0 10px;
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.14);
}
.audit-loading,
.audit-error,
.restored-note {
  margin: 24px 0;
  padding: 18px;
  border-radius: 8px;
  border: 1px solid var(--line);
  background: var(--panel);
}
.audit-loading,
.audit-error {
  display: grid;
  gap: 5px;
}
.audit-error {
  border-color: rgba(190, 18, 60, 0.3);
  background: #fff7f8;
  color: var(--rose);
}
.restored-note {
  margin-top: 0;
  color: var(--muted);
}
.audit-results {
  display: grid;
  gap: 18px;
  margin: 42px 0;
}
.score-panel {
  display: grid;
  grid-template-columns: 180px minmax(0, 1fr);
  gap: 24px;
  align-items: center;
  padding: clamp(22px, 4vw, 36px);
  border-radius: 8px;
  border: 1px solid var(--line);
  background: var(--panel);
  box-shadow: 0 12px 40px rgba(18, 21, 27, 0.05);
}
.score-ring {
  display: grid;
  place-items: center;
  align-content: center;
  width: 164px;
  height: 164px;
  border-radius: 50%;
  color: var(--ink);
  background:
    radial-gradient(circle at center, white 0 58%, transparent 59%),
    conic-gradient(var(--green), var(--blue), var(--gold), var(--rose), var(--green));
}
.score-ring span {
  font-size: 34px;
  font-weight: 950;
  line-height: 1;
}
.score-ring strong {
  font-size: 44px;
  line-height: 1;
}
.score-ring small {
  color: var(--muted);
  font-weight: 800;
}
.audit-meta,
.category-strip {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.audit-chip {
  display: inline-flex;
  align-items: center;
  min-height: 28px;
  padding: 0 10px;
  border-radius: 999px;
  font-size: 12px;
  font-weight: 900;
  background: #eef2f7;
  color: var(--muted);
}
.audit-chip.ok {
  background: #dff8ee;
  color: #066148;
}
.audit-chip.warn {
  background: #ffe8e8;
  color: #9f1239;
}
.share-panel {
  display: grid;
  grid-template-columns: minmax(180px, 0.75fr) minmax(220px, 1fr) auto;
  gap: 10px;
  align-items: center;
  margin-top: 18px;
  padding: 12px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
}
.share-panel strong,
.share-panel span {
  display: block;
}
.share-panel span {
  color: var(--muted);
  font-size: 13px;
  line-height: 1.35;
}
.share-panel input {
  min-height: 40px;
  width: 100%;
  padding: 0 11px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: white;
  color: var(--muted);
  font: inherit;
  font-size: 13px;
}
.share-panel button,
.competitor-actions a {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-height: 40px;
  padding: 0 12px;
  border-radius: 8px;
  font: inherit;
  font-size: 13px;
  font-weight: 900;
}
.share-panel button {
  border: 0;
  background: var(--ink);
  color: white;
  cursor: pointer;
}
.category-strip {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
}
.category-strip div {
  display: grid;
  gap: 6px;
  min-height: 86px;
  padding: 14px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
}
.category-strip span {
  color: var(--muted);
  font-size: 12px;
  font-weight: 900;
  text-transform: uppercase;
}
.category-strip strong {
  font-size: 30px;
}
.traffic-outlook-panel {
  display: grid;
  gap: 16px;
  padding: clamp(20px, 4vw, 28px);
  border: 1px solid rgba(159, 18, 57, 0.16);
  border-radius: 8px;
  background: linear-gradient(180deg, #fff8f8, #ffffff);
  box-shadow: 0 12px 34px rgba(159, 18, 57, 0.06);
}
.traffic-kpis,
.traffic-grid {
  display: grid;
  gap: 14px;
}
.traffic-kpis {
  grid-template-columns: repeat(4, minmax(0, 1fr));
}
.traffic-kpis div,
.traffic-grid article {
  padding: 16px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: white;
}
.traffic-kpis span,
.traffic-kpis em,
.traffic-grid span {
  color: var(--muted);
}
.traffic-kpis span {
  display: block;
  font-size: 12px;
  font-weight: 900;
  text-transform: uppercase;
}
.traffic-kpis strong {
  display: block;
  margin: 4px 0;
  font-size: 24px;
  line-height: 1.08;
}
.traffic-kpis em {
  font-style: normal;
}
.traffic-grid {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.traffic-grid ul {
  display: grid;
  gap: 10px;
  padding: 0;
  margin: 14px 0 0;
  list-style: none;
}
.traffic-grid li {
  padding-top: 10px;
  border-top: 1px solid #edf1f6;
  color: var(--muted);
}
.traffic-grid li:first-child {
  padding-top: 0;
  border-top: 0;
}
.google-ai-panel {
  display: grid;
  gap: 16px;
  padding: clamp(20px, 4vw, 28px);
  border: 1px solid rgba(37, 99, 235, 0.18);
  border-radius: 8px;
  background: linear-gradient(180deg, #f8fbff, #ffffff);
  box-shadow: 0 12px 34px rgba(37, 99, 235, 0.06);
}
.google-ai-kpis,
.google-ai-grid {
  display: grid;
  gap: 14px;
}
.google-ai-kpis {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}
.google-ai-kpis div,
.google-ai-grid article {
  padding: 16px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: white;
}
.google-ai-kpis span,
.google-ai-kpis em,
.google-ai-grid span,
.google-ai-grid em {
  color: var(--muted);
}
.google-ai-kpis span {
  display: block;
  font-size: 12px;
  font-weight: 900;
  text-transform: uppercase;
}
.google-ai-kpis strong {
  display: block;
  margin: 4px 0;
  font-size: 26px;
  line-height: 1.05;
}
.google-ai-kpis em,
.google-ai-grid em {
  font-style: normal;
}
.google-ai-grid {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}
.google-ai-grid ul {
  display: grid;
  gap: 10px;
  padding: 0;
  margin: 14px 0 0;
  list-style: none;
}
.google-ai-grid li {
  display: grid;
  gap: 4px;
  padding-top: 10px;
  border-top: 1px solid #edf1f6;
}
.google-ai-grid li:first-child {
  padding-top: 0;
  border-top: 0;
}
.google-ai-grid a {
  display: inline-flex;
  margin-left: 6px;
  color: var(--blue);
  font-weight: 900;
}
.audit-facts,
.opportunity-panel,
.checks-grid,
.competitor-list > div:last-child {
  display: grid;
  gap: 14px;
}
.audit-facts {
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
.audit-facts article,
.opportunity-panel,
.check-card,
.competitor-list {
  padding: 20px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: var(--panel);
  box-shadow: 0 10px 30px rgba(18, 21, 27, 0.045);
}
.audit-facts ul,
.opportunity-panel ul {
  display: grid;
  gap: 10px;
  padding: 0;
  margin: 14px 0 0;
  list-style: none;
}
.audit-facts li,
.opportunity-panel li {
  display: grid;
  gap: 3px;
  padding-top: 10px;
  border-top: 1px solid #edf1f6;
}
.audit-facts li:first-child,
.opportunity-panel li:first-child {
  padding-top: 0;
  border-top: 0;
}
.audit-facts span,
.opportunity-panel span {
  color: var(--muted);
  overflow-wrap: anywhere;
}
.opportunity-panel {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.opportunity-panel > div:first-child {
  grid-column: 1 / -1;
}
.checks-grid {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}
.check-card {
  display: grid;
  gap: 10px;
  align-content: start;
  min-height: 212px;
  border-top: 4px solid var(--green);
}
.check-card.fail {
  border-top-color: var(--rose);
}
.check-card > div {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}
.check-card small {
  color: var(--muted);
  font-weight: 800;
  text-transform: uppercase;
}
.check-card p {
  margin: 0;
  font-size: 14px;
}
.check-card strong {
  color: var(--ink);
  line-height: 1.45;
}
.competitor-list > div:last-child {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.competitor-list article {
  display: grid;
  gap: 10px;
}
.competitor-main {
  display: grid;
  gap: 8px;
  padding: 16px;
  border: 1px solid var(--line);
  border-radius: 8px;
  background: #fbfcfe;
}
.competitor-main:hover {
  border-color: #9db7d8;
}
.competitor-list small {
  color: var(--blue);
  font-weight: 900;
}
.competitor-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.competitor-actions a {
  border: 1px solid var(--line);
  background: var(--panel);
  color: var(--blue);
}
.competitor-actions a:last-child {
  background: var(--ink);
  border-color: var(--ink);
  color: white;
}
.footer {
  display: grid;
  grid-template-columns: minmax(240px, 0.34fr) minmax(0, 1fr);
  gap: 24px;
  margin-top: 72px;
  padding: 34px clamp(18px, 4vw, 54px) 48px;
  border-top: 1px solid var(--line);
}
.footer p {
  margin-bottom: 0;
}
@media (max-width: 920px) {
  .topbar {
    position: static;
    align-items: flex-start;
    flex-direction: column;
  }
  nav {
    justify-content: flex-start;
  }
  .hero,
  .split,
  .related-shell,
  .footer {
    grid-template-columns: 1fr;
  }
  .metrics,
  .trend-readout,
  .analytics-kpis,
  .flow-list,
  .gate-list,
  .audit-form,
  .traffic-kpis,
  .traffic-grid,
  .google-ai-kpis,
  .google-ai-grid,
  .category-strip,
  .audit-facts,
  .checks-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
  .score-panel,
  .opportunity-panel,
  .share-panel {
    grid-template-columns: 1fr;
  }
}
@media (max-width: 640px) {
  main {
    width: min(100% - 24px, 1180px);
  }
  h1,
  .page-hero h1 {
    font-size: 44px;
    line-height: 1.02;
  }
  .lead {
    font-size: 18px;
  }
  .metrics,
  .trend-readout,
  .analytics-kpis,
  .analytics-split,
  .related-grid,
  .oracle-grid,
  .lane-grid,
  .quality-detail,
  .flow-list,
  .gate-list,
  .audit-form,
  .traffic-kpis,
  .traffic-grid,
  .google-ai-kpis,
  .google-ai-grid,
  .category-strip,
  .audit-facts,
  .opportunity-panel,
  .checks-grid,
  .competitor-list > div:last-child {
    grid-template-columns: 1fr;
  }
  .metric {
    min-height: 128px;
  }
  .section-head {
    align-items: flex-start;
  }
  .section-actions {
    justify-content: flex-start;
    width: 100%;
  }
  .section-actions a {
    flex: 1;
    justify-content: center;
  }
  .trend-controls,
  .trend-controls label,
  .trend-presets,
  .trend-presets button {
    width: 100%;
  }
  .trend-axis {
    gap: 8px;
  }
  .score-panel {
    justify-items: start;
  }
  .score-ring {
    width: 142px;
    height: 142px;
  }
  .feedback-launch {
    right: 12px;
    bottom: 12px;
  }
  .feedback-actions {
    align-items: stretch;
    flex-direction: column;
  }
  .feedback-actions button {
    width: 100%;
  }
}
"""


def main() -> None:
    load_runtime_env()
    parser = argparse.ArgumentParser()
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", default=8106, type=int)
    args = parser.parse_args()
    server = ThreadingHTTPServer((args.host, args.port), Handler)
    print(f"CopeCheck SEO Lab listening on http://{args.host}:{args.port}", flush=True)
    server.serve_forever()


if __name__ == "__main__":
    main()
```
