#!/usr/bin/env python3
"""Check source contracts for the Lorem range fixtures and mobile Help route.

Run with the content repository (~/wiki), not the static/code repository, as
argument. This checks fixture inputs; it does not execute browser transclusion.
"""
import argparse
from html.parser import HTMLParser
from pathlib import Path
import re
import sys
from urllib.parse import urlsplit


def prose(source):
    """Exclude comments and fenced code examples from source-link checks."""
    fence = None
    lines = []
    for line in re.sub(r"<!--.*?-->", "", source, flags=re.S).splitlines():
        marker = re.match(r"^\s{0,3}(`{3,}|~{3,})", line)
        if marker and fence is None:
            fence = marker[1]
        elif marker and marker[1][0] == fence[0] and len(marker[1]) >= len(fence):
            fence = None
        elif fence is None:
            lines.append(line)
    return "\n".join(lines)


def includes(source):
    for match in re.finditer(r"\]\(([^()\s]+)\)\{([^{}\n]*)\}", prose(source)):
        classes = match[2].split()
        if ".include" in classes or ".include-strict" in classes:
            yield urlsplit(match[1]), classes


class MobileSpans(HTMLParser):
    """Keep text and icons in desktop-not spans, including nested icon spans."""
    def __init__(self):
        super().__init__()
        self.depth = 0
        self.parts = []
        self.spans = []

    def handle_starttag(self, tag, attrs):
        classes = dict(attrs).get("class", "").split()
        if tag == "span":
            if self.depth:
                self.depth += 1
            elif "desktop-not" in classes:
                self.depth = 1
                self.parts = []
        if self.depth:
            self.parts.extend(f"<{name}>" for name in classes if name.startswith("icon-"))

    def handle_endtag(self, tag):
        if tag == "span" and self.depth:
            self.depth -= 1
            if not self.depth:
                self.spans.append("".join(self.parts))

    def handle_data(self, data):
        if self.depth:
            self.parts.append(data)


def check(root):
    failures = []
    names = ["lorem", "lorem-header", "lorem-block", "lorem-list", "lorem-transclude", "help"]
    sources = {name: (root / f"{name}.md").read_text() for name in names}

    # Scope contracts: these fixtures must include the following sibling sections.
    # Full-page includes and explicit whole-page ranges are also sufficient.
    suites = [("lorem", "lorem-header", "Headers", "headers"),
              ("lorem", "lorem-block", "Block Elements", "block-elements"),
              ("lorem-block", "lorem-list", "Lists", "lists")]
    contracts = [(source, "/" + target, {"", ":", anchor + ":"}, True)
                 for source, target, _, anchor in suites]
    # Retain the three explicit range demonstrations, including the #: case.
    contracts += [("lorem-transclude", "/doc/math/humor/lion-hunting/abstract", {"history:"}, False),
                  ("lorem-transclude", "/doc/fiction/poetry/1963-valek-killingrabbits", {":"}, True),
                  ("lorem-transclude", "/lorem-link", {"internal-page-links:"}, True)]
    range_section = re.split(r"^## +Range Transcludes\b", sources["lorem-transclude"], flags=re.M | re.I)
    fixture_sources = dict(sources)
    fixture_sources["lorem-transclude"] = (re.split(r"^#{1,2} +", range_section[1], flags=re.M)[0]
                                         if len(range_section) == 2 else "")
    for source, target, fragments, strict in contracts:
        matches = [(url, classes) for url, classes in includes(fixture_sources[source])
                   if url.path == target and url.netloc in ("", "gwern.net")]
        if len(matches) != 1:
            failures.append(f"{source}.md: expected one include for {target}; found {len(matches)}")
        elif matches[0][0].fragment not in fragments or (strict and ".include-strict" not in matches[0][1]):
            failures.append(f"{source}.md: {target} must preserve its {'strict ' if strict else ''}range/suite scope")
    for _, target, title, _ in suites:
        headings = re.findall(r"^(#{1,6}) +([^\n]+)$", prose(sources[target]), re.M)
        if not headings or headings[0][1] != title or not any(len(level) <= len(headings[0][0]) for level, _ in headings[1:]):
            failures.append(f"{target}.md: expected first heading {title!r} and later sibling fixture sections")

    for path in root.glob("lorem*.md"):
        for url, _ in includes(path.read_text()):
            if url.netloc in ("", "gwern.net") and url.path.startswith("/") and "#" in url.fragment:
                failures.append(f"{path.name}: obsolete double-hash include: {url.geturl()}")

    mobile = MobileSpans()
    mobile.feed(sources["help"])
    instructions = [re.sub(r"[*_`]", "", span).lower() for span in mobile.spans
                    if re.search(r"disable\s+\**popovers", span, re.I)]
    if len(instructions) != 1:
        failures.append("help.md: expected one mobile-only Disable Popovers instruction")
    else:
        instruction = instructions[0]
        gear, off = "<icon-gear-solid>", "<icon-message-slash-solid>"
        before, separator, after = instruction.partition(gear)
        action, off_separator, _ = after.partition(off)
        if (not separator or not off_separator or "toolbar" not in action
                or not re.search(r"\bclose\s+(?:all|every)\b.*\bpopovers?\b", before)
                or not all(re.search(r"\b(?:tap|touch|press)\b", step) for step in (before, action))
                or re.search(r"\bhover\b|icon-eye-slash-solid", instruction)):
            failures.append("help.md: mobile Disable Popovers must close all popovers, then use touch actions on toolbar gear and message-slash controls")
    return failures


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("content_root", type=Path)
    parser.add_argument("--verbose", action="store_true")
    args = parser.parse_args()
    try:
        failures = check(args.content_root)
    except (OSError, UnicodeError, ValueError) as error:
        failures = [str(error)]
    for failure in failures:
        print("Content fixture regression: " + failure, file=sys.stderr)
    if args.verbose and not failures:
        print("Content fixtures: range syntax, sibling-suite coverage, and mobile Help route passed")
    return bool(failures)


if __name__ == "__main__":
    sys.exit(main())
