"""Reproduce the OCR row-pairing test on macOS with Pillow and Swift."""

import json
import statistics
import subprocess
import tempfile
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


EXPECTED = {
    "BRACKET": "12.40",
    "HINGE": None,
    "GASKET": "32.70",
    "CLIP": "18.50",
    "WASHER": "24.30",
}
ROOT = Path(__file__).resolve().parent


def make_fixture():
    image = Image.new("RGB", (1024, 456), "white")
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("/System/Library/Fonts/Menlo.ttc", size=40)
    for row, (label, price) in enumerate(EXPECTED.items()):
        y = 22 + row * 86
        draw.text((40, y), label, fill="black", font=font)
        if price is not None:
            draw.text((760, y), price, fill="black", font=font)
    return image


def read_column(image, box, path):
    image.crop(box).save(path)
    result = subprocess.run(
        ["swift", str(ROOT / "recognize.swift"), str(path)],
        check=True, capture_output=True, text=True,
    )
    return sorted(json.loads(result.stdout), key=lambda line: line["y"])


def pair_by_height(labels, prices):
    gaps = [b["y"] - a["y"] for a, b in zip(labels, labels[1:])]
    tolerance = 0.4 * statistics.median(gaps)
    paired = [None] * len(labels)
    for price in prices:
        row = min(range(len(labels)), key=lambda i: abs(price["y"] - labels[i]["y"]))
        if abs(price["y"] - labels[row]["y"]) > tolerance:
            raise ValueError(f"Unmatched price: {price}")
        if paired[row] is not None:
            raise ValueError(f"Ambiguous price for row {row + 1}")
        paired[row] = price["text"]
    return [(label["text"], price) for label, price in zip(labels, paired)]


def main():
    image = make_fixture()
    with tempfile.TemporaryDirectory() as directory:
        scratch = Path(directory)
        labels = read_column(image, (0, 0, 600, image.height), scratch / "items.png")
        prices = read_column(image, (600, 0, image.width, image.height), scratch / "prices.png")
    print("Labels read:", [line["text"] for line in labels])
    print("Prices read:", [line["text"] for line in prices])
    if len(labels) < 2:
        raise ValueError("At least two detected row labels are needed to estimate row spacing")
    naive = [(label["text"], price["text"]) for label, price in zip(labels, prices)]
    corrected = pair_by_height(labels, prices)
    expected_rows = list(EXPECTED.items())
    for name, rows in [("By index", naive), ("By height", corrected)]:
        matches = sum(a == b for a, b in zip(rows, expected_rows))
        print(f"{name}: {matches}/{len(expected_rows)} rows match", rows)
    assert corrected == expected_rows, "Mismatch against the generated fixture"


if __name__ == "__main__":
    main()
