"""Report the paragraph order found in extracted text.

Paragraphs in the fixture start with markers P1..P8. Paste or save any
extraction (copy-paste, pdftotext, a translation tool's source preview)
to a text file and run:

    python check_reading_order.py extracted.txt

A clean extraction prints P1 P2 P3 P4 P5 P6 P7 P8 with no line mixing.
"Mixed lines" counts lines that contain text from both columns, which is
what happens when a tool reads straight across the page.
"""
import re
import sys

LEFT_WORDS = {"river", "survey", "laser", "irrigation", "authority", "measure"}
RIGHT_WORDS = {"capstones", "repairs", "farmers", "calendar", "mill", "lock", "engineers", "shallowest"}


def main(path):
    text = open(path, encoding="utf-8").read()
    order = []
    for marker in re.findall(r"P([1-8])(?= )", text):
        if marker not in order:
            order.append(marker)
    mixed = 0
    for line in text.splitlines():
        words = set(re.findall(r"[a-z]+", line.lower()))
        if words & LEFT_WORDS and words & RIGHT_WORDS:
            mixed += 1
    expected = [str(i) for i in range(1, 9)]
    print("Order found:  ", " ".join("P" + m for m in order))
    print("In order:     ", "yes" if order == expected else "no")
    print("Missing:      ", " ".join("P" + m for m in expected if m not in order) or "none")
    print("Mixed lines:  ", mixed)


if __name__ == "__main__":
    main(sys.argv[1])
