#!/usr/bin/env python3
"""Add fraction/separator markup to HTML text without rewriting tags or attributes.

Used by sync.sh after HTML generation. Preserve the input byte-for-byte outside
changed text nodes: serializing a parsed DOM would also rewrite unrelated HTML.
"""

import argparse
from html.parser import HTMLParser
from pathlib import Path
import re


VOID_ELEMENTS = frozenset("area base br col embed hr img input link meta param source track wbr".split())
LITERAL_ELEMENTS = frozenset("script style title textarea pre code xmp iframe noembed noframes plaintext".split())
LITERAL_CLASSES = frozenset(("fraction", "separator-inline", "math", "MathJax", "mjx-chtml"))
FRACTION = re.compile(r"\b([0-9]{1,4})⁄([0-9]{1,4})\b")


class TextTypography(HTMLParser):
    def __init__(self, source, mode):
        super().__init__(convert_charrefs=False)
        self.source = source
        self.mode = mode
        self.stack = []
        self.edits = []
        self.line_starts = [0] + [match.end() for match in re.finditer("\n", source)]

    def handle_starttag(self, tag, attrs):
        if tag not in VOID_ELEMENTS:
            classes = dict(attrs).get("class") or ""
            literal = tag in LITERAL_ELEMENTS or bool(LITERAL_CLASSES.intersection(classes.split()))
            self.stack.append((tag, literal))

    def handle_startendtag(self, tag, attrs):
        pass

    def handle_endtag(self, tag):
        for i in range(len(self.stack) - 1, -1, -1):
            if self.stack[i][0] == tag:
                del self.stack[i:]
                break

    def handle_data(self, data):
        if any(literal for _, literal in self.stack):
            return
        if self.mode == "fraction":
            replacement = FRACTION.sub(r'<span class="fraction">\1⁄\2</span>', data)
        else:
            replacement = data.replace(" • ", ' <span class="separator-inline">•</span> ')
        if replacement != data:
            line, column = self.getpos()
            start = self.line_starts[line - 1] + column
            self.edits.append((start, start + len(data), replacement))


def transform(source, mode):
    parser = TextTypography(source, mode)
    parser.feed(source)
    parser.close()
    parts = []
    end = 0
    for start, stop, replacement in parser.edits:
        parts.extend((source[end:start], replacement))
        end = stop
    parts.append(source[end:])
    return "".join(parts)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("mode", choices=("fraction", "separator"))
    parser.add_argument("files", nargs="+", type=Path)
    args = parser.parse_args()
    for path in args.files:
        with path.open(encoding="utf-8", newline="") as handle:
            source = handle.read()
        result = transform(source, args.mode)
        if result != source:
            with path.open("w", encoding="utf-8", newline="") as handle:
                handle.write(result)


if __name__ == "__main__":
    main()
