#!/usr/bin/env python3
"""Compare selected order lines in the Texas EMAT district and title PDFs.

Download the same dated editions of Disbursements by District and by Title from
the Texas Education Agency instructional-materials funding page. Requires
Python 3.10+ and the free Poppler pdftotext command. Run locally:

    python3 check-orders.py district-report.pdf title-report.pdf

Only aggregate results are printed. Prices describe program and material orders
with the selected names. The two editions present the same underlying records.
"""
import argparse
from collections import Counter
from decimal import Decimal
from hashlib import sha256
import json
from pathlib import Path
import re
import subprocess

HEADERS = ("Title", "Transaction", "Publisher", "District", "Material", "Grade",
           "Subject Area", "Students", "Quantity", "Unit Price", "Extended")
DATE = re.compile(r"\d{2}/\d{2}/\d{4}")
NUMBERS = re.compile(r"\s+([\d,]+)\s+([\d,]+)\s+\$([\d.,]+)\s+\$([\d.,]+)\s*$")
TITLE = re.compile(r"pharmacy (?:tech|tecnician|practice for technicians)|pharm\s?tech|"
                   r"pharma\s?seer|\b(?:excpt|cpht|ptce|ptcb)\b", re.I)
EDITION = re.compile(r"(\d{4}-\d{4})\s+Biennium\s+\|\s+([A-Za-z]+)\s+(\d+,)\s+(\d{4})")

def clean(parts):
    # The two sorts wrap words at different page breaks, including after a hyphen.
    text = " ".join(" ".join(parts).split())
    return re.sub(r"(?<=\d)- (?=\d|year)", "-", text)

def comparison_key(row):
    fields, date, numbers = row
    title, _, publisher, district, material, grade, subject = map(clean, fields)
    if not TITLE.search(title):
        return None
    students, quantity, unit, extended = numbers
    qty, price, amount = int(quantity.replace(",","")), Decimal(unit.replace(",","")), Decimal(extended.replace(",",""))
    if price * qty != amount:
        raise ValueError(f"Quantity and unit price differ from extended amount for {district}, {date}")
    return (title, district, date, publisher, material, grade, subject, int(students.replace(",","")), qty, price, amount)

def read_report(path, ordering):
    raw = subprocess.run(["pdftotext", "-fixed", "2.6", str(path), "-"], check=True, capture_output=True).stdout
    pages = raw.decode("utf-8").split("\f")
    heading = " ".join(pages[0].split()[:38])
    edition_match = EDITION.search(heading)
    if "Disbursements - By " + ordering not in heading or not edition_match:
        raise ValueError(f"{path} does not identify the expected report and edition")
    selected = Counter()
    total = 0
    current = None

    def finish(row):
        if row is not None:
            key = comparison_key(row)
            if key is not None:
                selected[key] += 1

    for page_number, page in enumerate(pages, 1):
        if not page.strip():
            continue
        lines = page.splitlines()
        h = next((i for i,s in enumerate(lines) if s.lstrip().startswith("Title") and "Unit Price" in s), None)
        if h is None:
            raise ValueError(f"Table heading missing at {path}, p. {page_number}")
        starts = [lines[h].index(label) for label in HEADERS]
        breaks = [0] + [x - 1 for x in starts[1:8]]
        for line in lines[h+2:]:
            if not line.strip():
                continue
            date = DATE.search(line, starts[1] - 3, starts[2] + 1)
            if date:
                finish(current)
                numbers = NUMBERS.search(line)
                if not numbers:
                    raise ValueError(f"Unrecognized quantity or price at {path}, p. {page_number}")
                current = ([[] for _ in range(7)], date[0], numbers.groups())
                total += 1
            if current is None:
                continue
            for index, (left, right) in enumerate(zip(breaks, breaks[1:])):
                part = line[left:right].strip()
                if index != 1 and part:
                    current[0][index].append(part)
    finish(current)
    return (" ".join(edition_match[0].split()), total, selected)

def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("district", type=Path)
    parser.add_argument("title", type=Path)
    options = parser.parse_args()
    edition, all_rows, lines = read_report(options.district, "District")
    comparison = read_report(options.title, "Title")
    if (edition, all_rows, lines) != comparison:
        raise SystemExit("The edition, full row count or selected line multiset differs. Review before using totals.")
    amount = sum((row[-1] * n for row, n in lines.items()), Decimal(0))
    print(json.dumps({
        "edition": edition, "dated_order_lines_per_report": all_rows,
        "selected_lines": sum(lines.values()), "selected_districts": len({row[1] for row in lines}),
        "extended_amount_usd": str(amount),
        "district_report_sha256": sha256(options.district.read_bytes()).hexdigest(),
        "title_report_sha256": sha256(options.title.read_bytes()).hexdigest()
    }, indent=2))

if __name__ == "__main__":
    main()
