#!/usr/bin/env python3
"""Check one hreflang cluster from its HTML <head> annotations (educational example).

What it checks, starting from one URL:
  1. The start URL can be fetched and returns HTTP 200 (redirects are NOT followed).
  2. The start page has at least one usable <link rel="alternate" hreflang> annotation.
  3. The start page lists itself (self-reference).
  4. Every annotated target returns HTTP 200 without a redirect.
  5. Every target links back to the start URL (return link) and lists itself. Return
     links are checked to the start URL only, not between every pair of targets.
  6. The start page and every target carry no robots "noindex"/"none". All
     <meta name="robots"> tags and all X-Robots-Tag headers are combined, so a later
     permissive tag never erases an earlier noindex.
  7. A declared rel=canonical on the start page or a target points to that page itself.
     In a group of genuine translations, a canonical pointing to another URL is reported
     as a PROBLEM. The x-default target is exempt from this canonical check (it is often
     a shared fallback page), but it must still return 200, link back and list itself.
     A canonical is a signal; Google still selects the canonical itself.
  8. An hreflang value declared twice on the start page with different URLs is reported
     as a PROBLEM (only the last URL would otherwise be fetched).
  x-default is reported as information only; it is optional.

URL comparison: scheme and host are case-insensitive, percent-encoding is normalised
(raw UTF-8 equals its %XX form; escapes of reserved characters such as %2F stay
distinct), the fragment is ignored, and a trailing slash is significant.

What it does NOT do: render JavaScript, read hreflang from HTTP Link headers or
XML sitemaps, validate language/region codes, read crawler-specific meta tags such as
<meta name="googlebot">, check robots.txt, or tell you what Google indexed.
It sees the initial HTTP response only. Use URL Inspection for Google's view.

Exit codes: 0 = no problems found in the checks above (not proof of indexing, canonical
selection or complete hreflang correctness), 1 = problems found, 2 = the cluster could
not be checked (start fetch failed, non-200, or no annotations).
"""
import re
import sys
import urllib.error
import urllib.request
from html.parser import HTMLParser
from urllib.parse import quote, urljoin, urlsplit, urlunsplit

TIMEOUT = 15


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):  # keep 3xx visible as a status
        return None


OPENER = urllib.request.build_opener(NoRedirect)


def fetch(url):
    """Return (status, body, x_robots). status is None when the fetch itself failed."""
    req = urllib.request.Request(url, headers={"User-Agent": "hreflang-check/1.0"})
    try:
        with OPENER.open(req, timeout=TIMEOUT) as r:
            return r.status, r.read().decode("utf-8", "replace"), ", ".join(r.headers.get_all("X-Robots-Tag") or [])
    except urllib.error.HTTPError as e:  # 3xx, 4xx, 5xx
        return e.code, "", (", ".join(e.headers.get_all("X-Robots-Tag") or []) if e.headers else "")
    except (urllib.error.URLError, OSError, ValueError) as e:
        return None, f"fetch failed: {e}", ""


class Head(HTMLParser):
    def __init__(self, base):
        super().__init__()
        self.base, self.canonical, self.alts, self.robots, self.dupes = base, None, {}, [], set()

    def handle_starttag(self, tag, attrs):
        a = {k.lower(): (v or "").strip() for k, v in attrs}
        rel = a.get("rel", "").lower().split()
        if tag == "link" and "canonical" in rel and a.get("href"):
            self.canonical = urljoin(self.base, a["href"])
        if tag == "link" and "alternate" in rel and a.get("hreflang") and a.get("href"):
            lang, href = a["hreflang"].lower(), urljoin(self.base, a["href"])
            if lang in self.alts and norm(self.alts[lang]) != norm(href):
                self.dupes.add(lang)  # conflicting duplicate: reported, so no URL is silently dropped
            self.alts[lang] = href
        if tag == "meta" and a.get("name", "").lower() == "robots":
            self.robots.append(a.get("content", ""))  # accumulate: a later tag never erases noindex


UNRESERVED = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")


def _pct(s):
    # Percent-encode non-ASCII (UTF-8) and spaces, keep reserved characters and existing
    # escapes, upper-case escape hex, and decode only escapes of unreserved characters.
    # So /fa/درباره-ما equals its %D8%AF… form, but %2F stays distinct from "/".
    s = quote(s, safe="!#$&'()*+,/:;=?@[]~%")
    return re.sub(
        r"%([0-9A-Fa-f]{2})",
        lambda m: chr(int(m.group(1), 16)) if chr(int(m.group(1), 16)) in UNRESERVED else "%" + m.group(1).upper(),
        s,
    )


def norm(u):
    """Request identity of a URL: scheme and host lower-cased, path and query in one
    percent-encoding form (see _pct), fragment dropped, an empty path read as "/".
    A trailing slash is significant: /en and /en/ are different URLs."""
    p = urlsplit(u or "")
    return urlunsplit((p.scheme.lower(), p.netloc.lower(), _pct(p.path) or "/", _pct(p.query), ""))


def inspect(url):
    status, body, x_robots = fetch(norm(url))
    head = Head(url)
    if status == 200:
        head.feed(body)
    directives = (" ".join(head.robots) + " " + x_robots).lower()
    noindex = "noindex" in directives or "none" in directives.replace(",", " ").split()
    return status, body, head, noindex


def check(start):
    """Return (exit_code, report_lines)."""
    status, body, root, root_noindex = inspect(start)
    if status is None:
        return 2, [f"CANNOT CHECK: {start}: {body}"]
    if status != 200:
        return 2, [f"CANNOT CHECK: {start} returned HTTP {status} (expected 200; redirects are not followed)"]
    if not root.alts:
        return 2, [f"CANNOT CHECK: {start} has no usable hreflang annotations in its HTML head"]

    out, problems, warnings = [f"start {start}  status=200  annotations={len(root.alts)}"], [], []
    if norm(start) not in {norm(v) for v in root.alts.values()}:
        problems.append("start page does not list itself (self-reference missing)")
    for lang in sorted(root.dupes):
        problems.append(f"start page: hreflang \"{lang}\" is declared more than once with different URLs")
    if root_noindex:
        problems.append("start page: noindex")
    if root.canonical and norm(root.canonical) != norm(start):
        problems.append(f"start page: canonical points to {root.canonical}")
    if "x-default" not in root.alts:
        out.append("  note: no x-default (optional; recommended where a sensible fallback page exists)")

    for lang, target in sorted(root.alts.items()):
        if norm(target) == norm(start):
            continue
        t_status, t_body, t, t_noindex = inspect(target)
        if t_status is None:
            problems.append(f"{lang}: {t_body}")
            continue
        if t_status != 200:
            problems.append(f"{lang}: {target} returned HTTP {t_status} (hreflang targets should return 200)")
            continue
        back = norm(start) in {norm(v) for v in t.alts.values()}
        lists_self = norm(target) in {norm(v) for v in t.alts.values()}
        canon = "none" if not t.canonical else ("self" if norm(t.canonical) == norm(target) else t.canonical)
        out.append(f"  {lang:10} 200  return-link={back}  self-listed={lists_self}  canonical={canon}  noindex={t_noindex}")
        if not back:
            problems.append(f"{lang}: no return link to {start}")
        if not lists_self:
            problems.append(f"{lang}: does not list itself")
        if t_noindex:
            problems.append(f"{lang}: noindex")
        if t.canonical and canon != "self" and lang != "x-default":
            problems.append(f"{lang}: canonical points to {t.canonical}")

    out += [f"WARNING: {w}" for w in warnings]
    if problems:
        return 1, out + ["PROBLEMS:"] + [f"  - {p}" for p in problems]
    return 0, out + ["PASS: no problems found in the checks this script performs (not proof of indexing, canonical selection or complete hreflang correctness)."]


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: hreflang_check.py <start-url>")
    code, lines = check(sys.argv[1])
    print("\n".join(lines))
    sys.exit(code)
