"""Python 3.9+. Run with the path to the ZL3b-n.txt transcription."""
import hashlib
import random
import re
import sys
from collections import Counter
from pathlib import Path

data = Path(sys.argv[1]).read_bytes()
if hashlib.sha256(data).hexdigest() != "bf5b6d4ac1e3a51b1847a9c388318d609020441ccd56984c901c32b09beccafc":
    sys.exit("Expected the ZL 3b transcription dated 2025-05-13.")

def adjacent(words):
    return sum(left == right for left, right in zip(words, words[1:]))

eligible = used = pairs = observed = 0
expected = 0.0
repeated = []
for record in data.decode("latin1").splitlines():
    match = re.fullmatch(r"<(f[^.>]+)\.(\d+),.P[0t]>\s+(.+)", record)
    if not match:
        continue
    eligible += 1
    line = match[3].removeprefix("<%>").removesuffix("<$>")
    if not re.fullmatch(r"[a-z]+(?:\.[a-z]+)+", line):
        continue
    words = line.split(".")
    used += 1
    pairs += len(words) - 1
    observed += adjacent(words)
    counts = Counter(words)
    expected += sum(c * (c - 1) for c in counts.values()) / len(words)
    if len(counts) < len(words):
        repeated.append(words)

rng = random.Random(408)
samples = []
for trial in range(1000):
    total = 0
    for words in repeated:
        shuffled = words.copy()
        rng.shuffle(shuffled)
        total += adjacent(shuffled)
    samples.append(total)
samples.sort()
print("candidate lines, retained lines, pairs:", eligible, used, pairs)
print("observed, expected:", observed, expected)
print("25th and 975th ordered simulated counts:", samples[24], samples[974])
