"""Small initial-HTML regression gate; Python 3.9+, standard library only.

This checks project expectations, not Google indexing or rendered browser output.
Use a urlset sitemap, not a sitemap index. No redirects are followed.
"""

import argparse
import json
import re
import sys
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from pathlib import Path
from urllib.error import HTTPError
from urllib.parse import urljoin, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def fetch(url):
    request = Request(url, headers={"User-Agent": "SEORegressionExample/1.0"})
    try:
        response = build_opener(NoRedirect()).open(request, timeout=15)
    except HTTPError as error:
        response = error
    with response:
        return response.code, response.headers, response.read()


class Document(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.in_head = False
        self.in_title = False
        self.ignored = 0
        self.titles = []
        self.canonicals = []
        self.robots = []
        self.text = []
        self.links = []

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == "head":
            self.in_head = True
        if tag in ("script", "style", "template"):
            self.ignored += 1
        if self.ignored:
            return
        if tag == "title" and self.in_head:
            self.in_title = True
            self.titles.append("")
        if tag == "link" and self.in_head:
            if "canonical" in attrs.get("rel", "").lower().split():
                self.canonicals.append(attrs.get("href", ""))
        if tag == "meta" and attrs.get("name", "").lower() in ("robots", "googlebot"):
            self.robots.append(attrs.get("content", ""))
        if tag == "a" and "href" in attrs:
            self.links.append(attrs["href"])

    def handle_endtag(self, tag):
        if tag in ("script", "style", "template"):
            self.ignored = max(0, self.ignored - 1)
        if tag == "head":
            self.in_head = False
        if tag == "title":
            self.in_title = False

    def handle_data(self, data):
        if self.ignored:
            return
        if self.in_title:
            self.titles[-1] += data
        elif not self.in_head:
            self.text.append(data)


def check_case(base, case, sitemap_urls):
    path = case["path"]
    if not path.startswith("/") or path.startswith("//"):
        raise ValueError("case.path must start with a single slash")
    url = urljoin(base.rstrip("/") + "/", path)
    status, headers, raw = fetch(url)
    expected_status = case.get("status", 200)
    errors = []
    if status != expected_status:
        return [f"status {status}, expected {expected_status}"]
    if expected_status != 200:
        return errors
    if headers.get_content_type() != "text/html":
        return ["expected text/html"]
    page = Document()
    page.feed(raw.decode(headers.get_content_charset() or "utf-8"))
    if len(page.titles) != 1 or not page.titles[0].strip():
        errors.append("expected one nonempty title")
    elif case["title"] not in page.titles[0]:
        errors.append("title does not contain expected text")
    if page.canonicals != [case["canonical"]]:
        errors.append(f"canonical mismatch: {page.canonicals!r}")
    for value in headers.get_all("Link", []):
        for target, params in re.findall(r"<([^>]+)>([^,]*)", value):
            if re.search(r'''\brel\s*=\s*["']?canonical\b''', params, re.I):
                if target != case["canonical"]:
                    errors.append("HTTP Link canonical conflicts with expected URL")
    directives = page.robots + headers.get_all("X-Robots-Tag", [])
    if any(re.search(r"\b(noindex|none)\b", value, re.I) for value in directives):
        errors.append("noindex/none found in robots directives")
    text = " ".join(" ".join(page.text).split())
    if case["text"] not in text:
        errors.append("expected body text is missing from initial HTML")
    if case.get("link"):
        actual = {urljoin(url, href) for href in page.links}
        if urljoin(url, case["link"]) not in actual:
            errors.append("expected anchor link is missing")
    if sitemap_urls is not None and case["canonical"] not in sitemap_urls:
        errors.append("expected canonical URL is missing from sitemap")
    return errors


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base-url", required=True)
    parser.add_argument("--cases", required=True)
    parser.add_argument("--sitemap", help="Optional urlset path, for example /sitemap.xml")
    args = parser.parse_args()
    if urlsplit(args.base_url).scheme not in ("http", "https"):
        parser.error("--base-url must use http or https")
    cases = json.loads(Path(args.cases).read_text(encoding="utf-8"))
    if not isinstance(cases, list) or not cases:
        parser.error("--cases must contain a nonempty JSON array")
    sitemap_urls = None
    if args.sitemap:
        status, _, data = fetch(urljoin(args.base_url, args.sitemap))
        root = ET.fromstring(data)
        if status != 200 or root.tag.split("}")[-1] != "urlset":
            raise ValueError("sitemap must be a 200 response containing a urlset")
        sitemap_urls = {node.text.strip() for node in root.findall("./{*}url/{*}loc") if node.text}
    failures = 0
    for case in cases:
        try:
            errors = check_case(args.base_url, case, sitemap_urls)
        except Exception as error:
            errors = [f"request/check error: {error}"]
        failures += bool(errors)
        print(f"{'FAIL' if errors else 'PASS'} {case.get('path', '?')}")
        for error in errors:
            print(f"  - {error}")
    print(f"{len(cases) - failures}/{len(cases)} cases passed")
    return 1 if failures else 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as error:
        print(f"ERROR: {error}", file=sys.stderr)
        sys.exit(1)
