"""Align NE (Nepalese version) and V (vulgate 1938) chapter by chapter, letter by letter,
and classify every word.

Item types in the output stream of each chapter:
  k  kept      (same letters in both, after orthographic normalisation)
  c  changed   (the vulgate word partly agrees with the Nepalese)
  a  added     (vulgate only)
  d  dropped   (Nepalese only)
Each item: [type, vulgate form, Nepalese form, unit index]
"""
import json, re, sys, unicodedata, collections
import edlib
from diff_match_patch import diff_match_patch

VOW = set("aāiīuūṛṝḷḹeo")
CONS = set("kgcjṭḍtdpbnmṅñṇyrlvśṣshḥṃ") - set("ḥṃ")
NASAL = set("ṃṅñṇnm")


def clean(t, vulgate=False):
    t = unicodedata.normalize("NFC", t)
    t = re.sub(r"\[[^\[\]]*\d[^\[\]]*\]", " ", t)          # [cf. 1938 ed. 1.1.1] etc.
    t = re.sub(r"\[[^\[\]]*(?:colophon|cf\.|ed\.)[^\[\]]*\]", " ", t)
    if vulgate:
        t = re.sub(r"\([^()]{1,15}\)", "", t)       # bracketed alternative letters
    t = t.replace("m̐", "ṃ").replace("ṁ", "ṃ").replace("̐", "")
    t = re.sub(r"[|।॥0-9\[\]{}()…\-–—,.;:?!+*/=\"“”‘’]", " ", t)
    t = t.replace("`", "").replace("'", "").replace("ʼ", "").replace("’", "")
    return [w for w in t.split() if w]


def normalise(chars):
    """Fold orthographic and sandhi variants letter by letter (None = letter dropped).
    Both texts are folded the same way, so the folding only hides differences, never makes them."""
    n = len(chars)
    c1 = list(chars)
    for i, c in enumerate(c1):
        nxt = c1[i + 1] if i + 1 < n else ""
        if c == "b":
            c1[i] = "v"
        elif c == "m":
            c1[i] = "ṃ"                       # m / ṃ (final m before vowel vs anusvāra)
        elif c in "ṅñṇn" and (nxt == "" or nxt in CONS or nxt == "b"):
            c1[i] = "ṃ"                       # homorganic nasal before consonant
        elif c in "sśṣ" and nxt in ("k", "c", "ṭ", "t", "p"):
            c1[i] = "ḥ"                       # visarga sandhi: laghuś ca / laghuḥ
    out = [None] * n
    for i, c in enumerate(c1):
        nxt = c1[i + 1] if i + 1 < n else ""
        if c in CONS and c != "h" and nxt == c:
            continue                          # geminates: tt, rmm, ddh, cch
        if c in "sśṣ" and nxt == c:
            continue                          # aḥ s- / as s-
        if c == "ḥ":
            continue                          # visarga dropped ...
        if c == "a" and nxt == "ḥ":
            c = "o"                           # ... after aḥ -> o (rūkṣaḥ / rūkṣo)
        out[i] = c
    return out


def build(tokens):
    """tokens: list of (unit, word). Returns normalised string and char->token index list."""
    letters, owner = [], []
    for ti, (_, w) in enumerate(tokens):
        for ch in w:
            letters.append(ch)
            owner.append(ti)
    norm = normalise(letters)
    s, own = [], []
    for ch, o in zip(norm, owner):
        if ch is None:
            continue
        s.append(ch); own.append(o)
    return "".join(s), own


def cigar_to_diffs(cigar, a, b):
    diffs = []
    i = j = 0
    for num, op in re.findall(r"(\d+)([=XID])", cigar):
        num = int(num)
        if op == "=":
            diffs.append((0, a[i:i + num])); i += num; j += num
        elif op == "X":
            diffs.append((-1, a[i:i + num])); diffs.append((1, b[j:j + num])); i += num; j += num
        elif op == "I":          # extra in query (a)
            diffs.append((-1, a[i:i + num])); i += num
        elif op == "D":          # extra in target (b)
            diffs.append((1, b[j:j + num])); j += num
    # merge neighbours of the same kind
    merged = []
    for d in diffs:
        if merged and merged[-1][0] == d[0]:
            merged[-1] = (d[0], merged[-1][1] + d[1])
        else:
            merged.append(d)
    return merged


dmp = diff_match_patch()


def align_chapter(ne_tok, v_tok):
    a, a_own = build(ne_tok)
    b, b_own = build(v_tok)
    if a and b:
        # edlib needs <256 symbols: map letters to code points
        alpha = {ch: chr(33 + k) for k, ch in enumerate(sorted(set(a) | set(b)))}
        aa = "".join(alpha[c] for c in a); bb = "".join(alpha[c] for c in b)
        res = edlib.align(aa, bb, mode="NW", task="path")
        diffs = cigar_to_diffs(res["cigar"], a, b)
        dmp.diff_cleanupSemantic(diffs)
    elif a:
        diffs = [(-1, a)]
    else:
        diffs = [(1, b)] if b else []

    a_match = [False] * len(a); b_match = [False] * len(b)
    a_pos = [0] * len(a); b_pos = [0] * len(b)
    b2a = [-1] * len(b)
    i = j = 0; pos = 0
    for op, txt in diffs:
        for _ in txt:
            if op == 0:
                a_match[i] = b_match[j] = True
                a_pos[i] = b_pos[j] = pos; b2a[j] = i
                i += 1; j += 1
            elif op == -1:
                a_pos[i] = pos; i += 1
            else:
                b_pos[j] = pos; j += 1
            pos += 1
    assert i == len(a) and j == len(b)

    # per-token statistics
    def stats(n, own, match, posl):
        tot = [0] * n; m = [0] * n; first = [None] * n
        for k, t in enumerate(own):
            tot[t] += 1; m[t] += match[k]
            if first[t] is None:
                first[t] = posl[k]
        return tot, m, first

    at, am, afirst = stats(len(ne_tok), a_own, a_match, a_pos)
    bt, bm, bfirst = stats(len(v_tok), b_own, b_match, b_pos)

    # assign each surviving NE token to the V token sharing most of its letters
    share = collections.defaultdict(collections.Counter)
    for j, ai in enumerate(b2a):
        if ai >= 0:
            share[a_own[ai]][b_own[j]] += 1
    ne_of_v = collections.defaultdict(list)
    dropped = []
    for t in range(len(ne_tok)):
        frac = am[t] / at[t] if at[t] else 0
        if at[t] and frac >= 0.5 and share[t]:
            vt = share[t].most_common(1)[0][0]
            ne_of_v[vt].append(t)
        else:
            dropped.append(t)

    items = []   # (sortpos, order, item)
    for t in range(len(v_tok)):
        frac = bm[t] / bt[t] if bt[t] else 0
        nes = ne_of_v.get(t, [])
        ne_form = " ".join(ne_tok[x][1] for x in nes)
        if frac >= 0.999:
            typ = "k"
        elif frac >= 0.5:
            typ = "c"
        else:
            typ = "a" if not nes else "c"
        p = bfirst[t] if bfirst[t] is not None else (items[-1][0] if items else 0)
        items.append((p, 1, [typ, v_tok[t][1], ne_form, v_tok[t][0]]))
    for t in dropped:
        p = afirst[t] if afirst[t] is not None else 0
        items.append((p, 0, ["d", "", ne_tok[t][1], ne_tok[t][0]]))
    items.sort(key=lambda x: (x[0], x[1]))
    return [x[2] for x in items]


def chap_key(xid):
    p = xid.split(".")
    return (int(p[1]), int(re.match(r"\d+", p[2]).group()))


units = json.load(open(sys.argv[1]))
TITLES = json.load(open("titles.json"))
chap = collections.OrderedDict()
for ver in ("NE", "V"):
    for xid, txt in units[ver]:
        k = chap_key(xid)
        chap.setdefault(k, {"NE": [], "V": []})
        for w in clean(txt, vulgate=(ver == "V")):
            chap[k][ver].append((xid, w))

STHANA = {1: "Sūtrasthāna", 2: "Nidānasthāna", 3: "Śārīrasthāna", 4: "Cikitsāsthāna",
          5: "Kalpasthāna", 6: "Uttaratantra"}
out = {"sthanas": STHANA, "chapters": []}
tally = collections.Counter()
for k in sorted(chap):
    ne, v = chap[k]["NE"], chap[k]["V"]
    items = align_chapter(ne, v)
    # compress unit ids into an index table
    uids = []
    uix = {}
    rows = []
    for typ, vf, nf, u in items:
        if u not in uix:
            uix[u] = len(uids); uids.append(u)
        rows.append([typ, vf, 1 if (typ == "k" and nf == vf) else nf, uix[u]])
        tally[typ] += 1
    c = collections.Counter(r[0] for r in rows)
    title = TITLES.get(f"{k[0]}.{k[1]}", "")
    out["chapters"].append({"s": k[0], "a": k[1], "t": title, "units": uids, "items": rows,
                            "neWords": len(ne), "vWords": len(v)})
    print(k, len(ne), len(v), dict(c), flush=True)
print(tally)
json.dump(out, open(sys.argv[2], "w"), ensure_ascii=False, separators=(",", ":"))
