"""Check index.html entry scripts and styles against a GitLab Pages artifact."""

import argparse
import posixpath
import re
import sys
from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import unquote, urljoin, urlsplit


class EntryAssets(HTMLParser):
    CDATA_CONTENT_ELEMENTS = ("script", "style", "title", "textarea", "xmp", "iframe", "noembed", "noframes", "noscript")

    def __init__(self):
        super().__init__()
        self.base = None
        self.assets = []
        self.inert = []

    def handle_starttag(self, tag, pairs):
        if tag in ("template", "noscript"):
            self.inert.append(tag)
        if self.inert:
            return
        attrs = dict(reversed(pairs))  # HTML keeps the first duplicate attribute.
        if tag == "base" and self.base is None and "href" in attrs:
            self.base = attrs["href"] or ""
        if tag == "script" and "src" in attrs:
            self.assets.append((self.getpos()[0], attrs["src"] or ""))
        if tag == "link":
            rel = set((attrs.get("rel") or "").lower().split())
            if rel & {"stylesheet", "modulepreload"} or (
                "preload" in rel and (attrs.get("as") or "").lower() in ("script", "style")
            ):
                self.assets.append((self.getpos()[0], attrs.get("href") or ""))

    def handle_endtag(self, tag):
        if self.inert and self.inert[-1] == tag:
            self.inert.pop()


def origin(url):
    if url.scheme not in ("http", "https") or not url.hostname or url.username is not None:
        raise ValueError("expected an HTTP(S) URL without credentials")
    port = url.port if url.port is not None else {"http": 80, "https": 443}[url.scheme]
    return (url.scheme, url.hostname.lower(), port)


def decoded_path(url):
    if re.search(r"%(?:2f|5c)|%(?![a-f0-9]{2})", url.path, re.I):
        raise ValueError("ambiguous URL path encoding")
    path = unquote(url.path, errors="strict")
    if "\\" in path or any(ord(c) < 32 for c in path):
        raise ValueError("invalid URL path")
    return posixpath.normpath("/" + path.lstrip("/"))


def check(output, site_url):
    site = urlsplit(site_url)
    site_origin = origin(site)
    if site.query or site.fragment or "\\" in site_url:
        raise ValueError("supply the Pages site URL including its project path")
    project = decoded_path(site).rstrip("/") + "/"
    document_url = site_url.rstrip("/") + "/index.html"
    root = output.resolve(strict=True)
    entry = (root / "index.html").resolve(strict=True)
    if not entry.is_relative_to(root) or not entry.is_file():
        raise ValueError("index.html must be a file inside the output directory")
    html = entry.read_text(encoding="utf-8-sig")
    if not html.strip():
        raise ValueError("index.html is empty")
    parser = EntryAssets()
    parser.feed(html)
    parser.close()
    base = urljoin(document_url, parser.base or "")
    checked = external = inline = errors = 0
    for line, ref in parser.assets:
        try:
            ref = ref.strip()
            if not ref or "\\" in ref or "\\" in base:
                raise ValueError("empty or invalid asset URL")
            url = urlsplit(urljoin(base, ref))
            if url.scheme == "data":
                inline += 1
                continue
            if origin(url) != site_origin:
                external += 1
                continue
            path = decoded_path(url)
            if not path.startswith(project):
                raise ValueError(f"asset outside Pages path {project}: {path}")
            filename = (root / path[len(project):]).resolve()
            if not filename.is_relative_to(root) or not filename.is_file():
                raise ValueError(f"file missing from published output: {path}")
            if filename == entry or url.path.endswith("/"):
                raise ValueError(f"expected an asset file: {path}")
            checked += 1
        except (ValueError, OSError, RuntimeError) as error:
            print(f"index.html line {line}: {error}", file=sys.stderr)
            errors += 1
    print(f"{checked} local entries verified, {external} external and {inline} inline entries skipped")
    return 1 if errors else 0


if __name__ == "__main__":
    args = argparse.ArgumentParser(description=__doc__)
    args.add_argument("output", type=Path, help="publish directory containing index.html")
    args.add_argument("site_url", help="Pages site URL including the project path")
    options = args.parse_args()
    try:
        sys.exit(check(options.output, options.site_url))
    except (ValueError, OSError, RuntimeError) as error:
        sys.exit(f"Build check failed: {error}")
