"""Usage: python3 voynich-ee-variants.py GC2a-n_Eva-VTDepot.txt ZL3b-n.txt IT2a-n.txt GC2a-n.txt

Scan ordinary paragraph lines. Positions are one-based indices of the left word.
SHA-256 checks identify the exact ASCII files used for the published comparison.
"""
from collections import Counter
import hashlib
import re
import sys
from pathlib import Path

HASHES = (
    "0b7bd8b9afdc50b042c6e6964813904a28e84af00bdecd06cda31d1f8a4ef16b",
    "bf5b6d4ac1e3a51b1847a9c388318d609020441ccd56984c901c32b09beccafc",
    "7f27a8b0feed8f6de0a99900df6bf912dd1d295c38e5f830bac8b41c3f536fb5",
    "b09570cb6c993bc2d87134d115e60a978650a8a6495483ddbb1f6005a586096f",
)


def read_rows(path, expected_hash):
    data = Path(path).read_bytes()
    if hashlib.sha256(data).hexdigest() != expected_hash:
        raise ValueError(f"Unexpected file version: {path}")
    rows = {}
    for record in data.decode("latin1").splitlines():
        match = re.fullmatch(r"<(f[^.>]+\.\d+),.P[0t]>\s+(.+)", record)
        if match:
            locus, line = match.groups()
            if locus in rows:
                raise ValueError(f"Duplicate locus: {locus}")
            line = line.removeprefix("<%>").removesuffix("<$>")
            # Keep annotated tokens in place and exclude them from comparison.
            line = re.sub(r"<[^>]*>", "?", line)
            rows[locus] = line.split(".")
    return rows


def base_spelling(word):
    if not re.fullmatch(r"(?:[a-z]|\{ee\})+", word):
        return None
    base = word.replace("{ee}", "ee")
    if base.count("ee") == 1 and "eee" not in base:
        return base
    return None


def compare(gc, zl, it):
    total = different = agreed = 0
    for locus, words in gc.items():
        z, t = zl.get(locus, []), it.get(locus, [])
        comparable = (len(z) == len(t) == len(words)
                      and all(re.fullmatch("[a-z]+", w) for w in z + t))
        for i, (a, b) in enumerate(zip(words, words[1:])):
            base = base_spelling(a)
            if base is None or base != base_spelling(b):
                continue
            total += 1
            if a != b:
                different += 1
                agreement = comparable and z[i:i+2] == t[i:i+2] == [base, base]
                agreed += int(agreement)
                print(locus, i + 1, a, b, "ZL+IT" if agreement else "-", sep="\t")
    print("Pairs after merging, also exact before merging, changed, ZL+IT matches:",
          total, total - different, different, agreed)


def audit_agreements(zl, it, native):
    counts = Counter()
    for locus, z in zl.items():
        t = it.get(locus, [])
        if len(z) != len(t) or not all(re.fullmatch("[a-z]+", w) for w in z + t):
            continue
        words = native.get(locus, [])
        for i in range(len(z) - 1):
            if z[i] != z[i + 1] or t[i] != t[i + 1]:
                continue
            counts["agreed"] += 1
            if len(words) != len(z):
                continue
            counts["same_length"] += 1
            a, b = words[i:i + 2]
            if not all(re.fullmatch("[A-Za-z0-9]+", w) for w in (a, b)):
                continue
            verdict = "same" if a == b else "different"
            counts[verdict] += 1
            if all(re.fullmatch("[A-Za-z0-9]+", w) for w in words):
                counts["whole_line_" + verdict] += 1
            if a != b:
                print(locus, i + 1, z[i], t[i], a, b, sep="\t")
    print(dict(counts))


if __name__ == "__main__":
    if len(sys.argv) != 5:
        sys.exit(__doc__)
    gc, zl, it, native = (read_rows(p, h) for p, h in zip(sys.argv[1:], HASHES))
    audit_agreements(zl, it, native)
    compare(gc, zl, it)
