"""Usage: python3 voynich-transcription-agreement.py ZL3b-n.txt IT2a-n.txt"""
import hashlib
import re
import sys
from pathlib import Path

def read_rows(path, expected_hash):
    raw = Path(path).read_bytes()
    if hashlib.sha256(raw).hexdigest() != expected_hash:
        sys.exit(f"Unexpected transcription version: {path}")
    rows = {}
    for record in raw.decode("latin1").splitlines():
        match = re.fullmatch(r"<(f[^.>]+\.\d+),.P[0t]>\s+(.+)", record)
        if not match:
            continue
        locus, text = match.groups()
        text = text.removeprefix("<%>").removesuffix("<$>")
        if re.fullmatch(r"[a-z]+(?:\.[a-z]+)+", text):
            if locus in rows:
                raise ValueError(f"Duplicate locus: {locus}")
            rows[locus] = text.split(".")
    return rows

def repeated_positions(rows, loci):
    return {
        (locus, index)
        for locus in loci
        for index, (a, b) in enumerate(zip(rows[locus], rows[locus][1:]))
        if a == b
    }

if len(sys.argv) != 3:
    sys.exit(__doc__)
zl = read_rows(sys.argv[1], "bf5b6d4ac1e3a51b1847a9c388318d609020441ccd56984c901c32b09beccafc")
it = read_rows(sys.argv[2], "7f27a8b0feed8f6de0a99900df6bf912dd1d295c38e5f830bac8b41c3f536fb5")
common = [key for key in zl.keys() & it.keys() if len(zl[key]) == len(it[key])]
first = repeated_positions(zl, common)
second = repeated_positions(it, common)
print("Comparable lines and adjacent pairs:", len(common), sum(len(zl[k]) - 1 for k in common))
print("ZL, IT, both, either:", len(first), len(second), len(first & second), len(first | second))
for locus, index in sorted(first ^ second):
    print(locus, index + 1, *zl[locus][index:index + 2], *it[locus][index:index + 2], sep="\t")
