"""Extract text units (by xml:id) from the NE and vulgate TEI files.

Output: units.json = {"NE": [[id, text], ...], "V": [[id, text], ...]} in document order.
"""
import json, re, sys, glob, os
from lxml import etree

TEI = "{http://www.tei-c.org/ns/1.0}"
XMLID = "{http://www.w3.org/XML/1998/namespace}id"
SKIP = {"note", "label", "head", "standOff", "rdg", "sic", "metamark", "pb", "fw",
        "orig", "del", "witDetail", "listWit", "interp"}
UNIT_TAGS = {"l", "lg", "p", "trailer", "ab", "seg"}
IDRE = re.compile(r"^SS\.\d+\.\d+")


def text_of(el):
    out = []

    def walk(e):
        tag = etree.QName(e).localname if isinstance(e.tag, str) else None
        if tag is None:            # comment / PI
            if e.tail: out.append(e.tail)
            return
        if tag in SKIP:
            pass
        elif tag == "choice":
            # prefer corr / reg / expan
            pick = None
            for want in ("corr", "reg", "expan"):
                pick = e.find(TEI + want)
                if pick is not None:
                    break
            if pick is not None:
                walk_inner(pick)
        elif tag in ("caesura", "lb", "cb"):
            out.append(" ")
        elif tag == "gap":
            out.append(" … ")
        else:
            walk_inner(e)
        if e.tail:
            out.append(e.tail)

    def walk_inner(e):
        if e.text:
            out.append(e.text)
        for c in e:
            walk(c)

    walk_inner(el)
    s = "".join(out)
    s = re.sub(r"\s+", " ", s).strip()
    return s


def units(path):
    tree = etree.parse(path)
    body = tree.find(f".//{TEI}body")
    res = []
    for el in body.iter():
        if not isinstance(el.tag, str):
            continue
        xid = el.get(XMLID)
        if not xid or not IDRE.match(xid):
            continue
        if etree.QName(el).localname not in UNIT_TAGS:
            continue
        # outermost only
        anc = el.getparent(); inner = False
        while anc is not None:
            if anc.get(XMLID) and IDRE.match(anc.get(XMLID)) and etree.QName(anc).localname in UNIT_TAGS:
                inner = True; break
            anc = anc.getparent()
        if inner:
            continue
        res.append([xid, text_of(el)])
    return res


root = sys.argv[1]
out = {"NE": [], "V": []}
for d in sorted(glob.glob(os.path.join(root, "0*"))):
    for f in sorted(os.listdir(d)):
        p = os.path.join(d, f)
        if f.startswith("provisional-edition_") and f.endswith("_new.xml"):
            out["NE"] += units(p)
        elif "vulgate-1938" in f and f.endswith(".xml"):
            out["V"] += units(p)
print({k: len(v) for k, v in out.items()})
print({k: sum(len(t.split()) for _, t in v) for k, v in out.items()})
json.dump(out, open(sys.argv[2], "w"), ensure_ascii=False)
