"""Convert Shanina's Word documents into Sanity Portable Text.

Word formatting is mapped onto the site's fixed vocabulary:
  * font size relative to the body size (20pt) -> size decorators
    sm / lg / xl / xxl (base size has no decorator)
  * bold -> strong
  * centered paragraphs -> the "center" block style
  * consecutive lines -> one block with soft line breaks; an empty paragraph
    starts a new block (a "stanza"), which matches how Shanina writes.
Red text is a note to the designer and white text is hidden duplicate text from
Word text boxes; both are dropped (red notes are returned separately).
"""
import hashlib
import re
import zipfile
import xml.etree.ElementTree as ET

W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
MC = "{http://schemas.openxmlformats.org/markup-compatibility/2006}"
BASE_SIZE = 40  # half-points
NOTE_COLORS = {"FF0000"}
HIDDEN_COLORS = {"FFFFFF"}


def size_mark(sz):
    if not sz:
        return None
    r = sz / BASE_SIZE
    if r <= 0.92:
        return "sm"
    if r < 1.05:
        return None
    if r <= 1.25:
        return "lg"
    if r <= 1.5:
        return "xl"
    return "xxl"


def _skip_ancestors(root):
    """Elements whose text must be ignored: text boxes and compat fallbacks."""
    skip = set()
    for tag in (W + "txbxContent", MC + "Fallback"):
        for el in root.iter(tag):
            for sub in el.iter():
                skip.add(sub)
    return skip


def read_paragraphs(path):
    """Returns paragraphs as dicts: {align, runs: [{text, size, bold}], notes}."""
    root = ET.fromstring(zipfile.ZipFile(path).read("word/document.xml"))
    skip = _skip_ancestors(root)
    out = []
    for p in root.iter(W + "p"):
        if p in skip:
            continue
        jc = p.find(f"{W}pPr/{W}jc")
        align = jc.get(W + "val") if jc is not None else None
        runs, notes = [], []
        for r in p.iter(W + "r"):
            if r in skip:
                continue
            rp = r.find(W + "rPr")
            sz = bold = color = None
            if rp is not None:
                s = rp.find(W + "sz")
                sz = int(s.get(W + "val")) if s is not None else None
                b = rp.find(W + "b")
                bold = b is not None and b.get(W + "val") not in ("0", "false")
                c = rp.find(W + "color")
                color = c.get(W + "val").upper() if c is not None else None
            text = ""
            for el in r:
                if el.tag == W + "t":
                    text += el.text or ""
                elif el.tag == W + "br":
                    text += "\n"
                elif el.tag == W + "tab":
                    text += " "
            if not text:
                continue
            if color in HIDDEN_COLORS:
                continue
            if color in NOTE_COLORS:
                notes.append(text)
                continue
            runs.append({"text": text, "size": size_mark(sz), "bold": bool(bold)})
        out.append({"align": align, "runs": runs, "notes": "".join(notes).strip()})
    return out


def para_text(p):
    return "".join(r["text"] for r in p["runs"]).strip()


def _key(*parts):
    return hashlib.md5("|".join(map(str, parts)).encode("utf8")).hexdigest()[:12]


def _marks(run):
    marks = []
    if run["bold"]:
        marks.append("strong")
    if run["size"]:
        marks.append(run["size"])
    return marks


def block(spans, style="normal", seed=""):
    """spans: list of (text, marks). Adjacent spans with equal marks merge."""
    children = []
    for text, marks in spans:
        if children and not text.strip(" "):
            marks = children[-1]["marks"]  # a bare space keeps its neighbour's marks
        if children and children[-1]["marks"] == marks:
            children[-1]["text"] += text
        else:
            children.append({"_type": "span", "text": text, "marks": marks})
    if children:
        children[0]["text"] = children[0]["text"].lstrip(" ")
        children[-1]["text"] = children[-1]["text"].rstrip(" \n")
    children = [c for c in children if c["text"]]
    for i, c in enumerate(children):
        c["_key"] = _key(seed, style, i, c["text"])
    return {"_type": "block", "_key": _key(seed, style, "b", *[c["text"] for c in children]),
            "style": style, "markDefs": [], "children": children}


def plain_block(text, style="normal", marks=None):
    return block([(text, list(marks or []))], style, seed=text)


def to_blocks(paragraphs, center=None):
    """Group paragraphs into stanza blocks. `center` overrides alignment."""
    blocks, stanza, stanza_center = [], [], False

    def flush():
        nonlocal stanza
        if stanza:
            spans = []
            for i, p in enumerate(stanza):
                if i:
                    spans.append(("\n", []))
                spans.extend((r["text"], _marks(r)) for r in p["runs"])
            style = "center" if stanza_center else "normal"
            blocks.append(block(spans, style, seed=para_text(stanza[0]) + str(len(blocks))))
            stanza = []

    for p in paragraphs:
        if not para_text(p):
            flush()
            continue
        is_center = (p["align"] == "center") if center is None else center
        if stanza and is_center != stanza_center:
            flush()
        stanza_center = is_center
        stanza.append(p)
    flush()
    return blocks


def slice_between(paragraphs, start, end=None, include_start=True):
    """Paragraphs from the first one starting with `start` up to (not including)
    the first later one starting with `end`."""
    def norm(s):
        return re.sub(r"\s+", " ", s).strip()

    texts = [norm(para_text(p)) for p in paragraphs]
    i = next(k for k, t in enumerate(texts) if t.startswith(norm(start)))
    j = len(paragraphs)
    if end is not None:
        j = next(k for k in range(i + 1, len(texts)) if texts[k].startswith(norm(end)))
    return paragraphs[i if include_start else i + 1:j]
