#!/usr/bin/env python3
"""Local receipt OCR demo with an explicit review and repair boundary."""

from __future__ import annotations

import csv
import hashlib
import re
import subprocess
import sys
from decimal import Decimal, InvalidOperation
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf"
FIELDS = [
    "receipt_id",
    "merchant",
    "date",
    "subtotal",
    "tax",
    "total",
    "arithmetic_status",
    "review_status",
    "review_reason",
    "source_sha256",
]


def write_csv(path: Path, rows: list[dict[str, str]], fields: list[str]) -> None:
    with path.open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def money(value: str) -> Decimal | None:
    try:
        return Decimal(value) if value else None
    except InvalidOperation:
        return None


def arithmetic_status(row: dict[str, str]) -> str:
    subtotal, tax, total = (money(row[key]) for key in ("subtotal", "tax", "total"))
    if None in (subtotal, tax, total):
        return "NOT_CHECKED"
    return "PASS" if subtotal + tax == total else "FAIL"


def make_receipt(path: Path, merchant: str, date: str, subtotal: str, tax: str,
                 total_label: str, total: str, note: str) -> None:
    image = Image.new("RGB", (900, 1120), "#f7f2e8")
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(FONT_PATH, 40)
    bold = ImageFont.truetype(FONT_PATH, 48)
    draw.rectangle((45, 35, 855, 1085), fill="white", outline="#c8c0b4", width=3)
    y = 90
    draw.text((100, y), merchant, font=bold, fill="black")
    y += 100
    for line in [
        f"DATE      {date}",
        "ITEM      OFFICE SUPPLIES",
        "QTY       1",
        "",
        f"SUBTOTAL  {subtotal}",
        f"TAX       {tax}",
        f"{total_label:<9} {total}",
    ]:
        draw.text((100, y), line, font=font, fill="black")
        y += 76
    draw.line((90, y + 10, 810, y + 10), fill="#777", width=2)
    draw.text((100, y + 55), note, font=ImageFont.truetype(FONT_PATH, 25), fill="#555")
    image.save(path, dpi=(300, 300))


def make_samples(input_dir: Path) -> None:
    if input_dir.exists() and any(input_dir.iterdir()):
        raise SystemExit("STOP input directory must be new or empty")
    input_dir.mkdir(parents=True, exist_ok=True)
    make_receipt(
        input_dir / "receipt-001.png", "NORTHLINE SUPPLY", "2026-11-12",
        "26.25", "2.10", "TOTAL", "28.35", "SYNTHETIC TRAINING RECEIPT",
    )
    make_receipt(
        input_dir / "receipt-002.png", "HARBOR TOOLS", "2026-11-13",
        "76.50", "6.12", "AM0UNT", "82.62", "SYNTHETIC DAMAGED TOTAL LABEL",
    )
    correction_fields = ["receipt_id", "field", "corrected_value", "reason", "reviewer"]
    write_csv(
        input_dir / "corrections.csv",
        [{
            "receipt_id": "receipt-002",
            "field": "total",
            "corrected_value": "82.62",
            "reason": "Read visible amount beside damaged total label",
            "reviewer": "sample-reviewer",
        }],
        correction_fields,
    )
    print("SAMPLES receipts=2 synthetic=true damaged_labels=1")
    print("FILES receipt-001.png receipt-002.png corrections.csv")


def ocr_lines(image_path: Path) -> tuple[list[str], list[float]]:
    command = [
        "tesseract", str(image_path), "stdout", "-l", "eng", "--psm", "6",
        "--dpi", "300", "tsv",
    ]
    result = subprocess.run(command, capture_output=True, text=True, check=False)
    if result.returncode != 0 or result.stderr:
        raise RuntimeError(f"tesseract failed for {image_path.name}: {result.stderr.strip()}")
    rows = list(csv.DictReader(result.stdout.splitlines(), delimiter="\t"))
    groups: dict[tuple[str, str, str, str], list[str]] = {}
    confidences: list[float] = []
    for row in rows:
        text = row.get("text", "").strip()
        if not text:
            continue
        key = (row["page_num"], row["block_num"], row["par_num"], row["line_num"])
        groups.setdefault(key, []).append(text)
        confidence = float(row["conf"])
        if confidence >= 0:
            confidences.append(confidence)
    return [" ".join(words) for words in groups.values()], confidences


def first_match(pattern: str, lines: list[str]) -> str:
    for line in lines:
        match = re.search(pattern, line, flags=re.IGNORECASE)
        if match:
            return match.group(1)
    return ""


def parse_receipt(image_path: Path, work_dir: Path) -> dict[str, str]:
    lines, confidences = ocr_lines(image_path)
    (work_dir / f"{image_path.stem}.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
    merchant = lines[0].strip() if lines else ""
    row = {
        "receipt_id": image_path.stem,
        "merchant": merchant,
        "date": first_match(r"DATE\s+(\d{4}-\d{2}-\d{2})", lines),
        "subtotal": first_match(r"SUBTOTAL\s+([0-9]+\.[0-9]{2})", lines),
        "tax": first_match(r"^TAX\s+([0-9]+\.[0-9]{2})", lines),
        "total": first_match(r"^TOTAL\s+([0-9]+\.[0-9]{2})", lines),
        "arithmetic_status": "",
        "review_status": "",
        "review_reason": "",
        "source_sha256": hashlib.sha256(image_path.read_bytes()).hexdigest(),
    }
    row["arithmetic_status"] = arithmetic_status(row)
    missing = [key for key in ("merchant", "date", "subtotal", "tax", "total") if not row[key]]
    if missing:
        row["review_status"] = "REVIEW"
        row["review_reason"] = "missing:" + ",".join(missing)
    elif row["arithmetic_status"] != "PASS":
        row["review_status"] = "REVIEW"
        row["review_reason"] = "arithmetic:" + row["arithmetic_status"].lower()
    else:
        row["review_status"] = "READY"
        row["review_reason"] = ""
    return row


def render_result(path: Path, rows: list[dict[str, str]], title: str) -> None:
    image = Image.new("RGB", (1500, 650), "#f3efe6")
    draw = ImageDraw.Draw(image)
    title_font = ImageFont.truetype(FONT_PATH, 42)
    body_font = ImageFont.truetype(FONT_PATH, 26)
    draw.text((55, 45), title, font=title_font, fill="#14213d")
    draw.text((55, 115), "ID          MERCHANT              TOTAL   CHECK        STATUS", font=body_font, fill="#444")
    y = 180
    for row in rows:
        color = "#9c2f1b" if row["review_status"] == "REVIEW" else "#176b45"
        text = f"{row['receipt_id']:<11} {row['merchant'][:20]:<20} {row['total'] or 'MISSING':>7}   {row['arithmetic_status']:<12} {row['review_status']}"
        draw.rounded_rectangle((40, y - 18, 1460, y + 65), radius=12, fill="white", outline=color, width=4)
        draw.text((65, y), text, font=body_font, fill="#111")
        if row["review_reason"]:
            draw.text((65, y + 38), row["review_reason"], font=ImageFont.truetype(FONT_PATH, 20), fill=color)
        y += 120
    draw.text((55, 545), "Executed locally. Synthetic receipts. No accounting-system write.", font=body_font, fill="#444")
    image.save(path)


def scan(input_dir: Path, work_dir: Path) -> None:
    if work_dir.exists():
        raise SystemExit("STOP work directory already exists")
    work_dir.mkdir(parents=True)
    images = sorted(input_dir.glob("receipt-*.png"))
    if not images:
        raise SystemExit("STOP no receipt-*.png files found")
    rows = [parse_receipt(path, work_dir) for path in images]
    write_csv(work_dir / "review_queue.csv", rows, FIELDS)
    render_result(work_dir / "review-result.png", rows, "Receipt OCR review queue")
    ready = sum(row["review_status"] == "READY" for row in rows)
    review = len(rows) - ready
    print("OCR tesseract=5.5.0 language=eng psm=6")
    print(f"INPUT receipts={len(rows)} synthetic=true")
    print(f"RESULT ready={ready} review={review}")
    for row in rows:
        if row["review_status"] == "REVIEW":
            print(f"REVIEW {row['receipt_id']} reason={row['review_reason']}")
    print(f"EXPORT review_queue.csv rows={len(rows)} review-result.png")
    print("CHECK HOLD: review rows must be repaired before export")


def approve(work_dir: Path, corrections_path: Path) -> None:
    queue_path = work_dir / "review_queue.csv"
    output_path = work_dir / "approved_receipts.csv"
    if output_path.exists():
        raise SystemExit("STOP approved export already exists")
    with queue_path.open(newline="", encoding="utf-8") as handle:
        rows = list(csv.DictReader(handle))
    with corrections_path.open(newline="", encoding="utf-8") as handle:
        corrections = list(csv.DictReader(handle))
    by_id = {row["receipt_id"]: row for row in rows}
    for correction in corrections:
        receipt_id = correction["receipt_id"]
        field = correction["field"]
        if receipt_id not in by_id or field not in ("merchant", "date", "subtotal", "tax", "total"):
            raise SystemExit("STOP correction references unknown receipt or field")
        if not correction["reason"].strip() or not correction["reviewer"].strip():
            raise SystemExit("STOP every correction needs a reason and reviewer")
        by_id[receipt_id][field] = correction["corrected_value"].strip()
    for row in rows:
        row["arithmetic_status"] = arithmetic_status(row)
        missing = [key for key in ("merchant", "date", "subtotal", "tax", "total") if not row[key]]
        if missing or row["arithmetic_status"] != "PASS":
            raise SystemExit(f"STOP {row['receipt_id']} still fails review")
        row["review_status"] = "APPROVED"
        row["review_reason"] = ""
    write_csv(output_path, rows, FIELDS)
    render_result(work_dir / "approved-result.png", rows, "Approved receipt export")
    total = sum(Decimal(row["total"]) for row in rows)
    print(f"CORRECTIONS applied={len(corrections)}")
    print(f"CHECK arithmetic_pass={len(rows)}/{len(rows)} missing_fields=0")
    print(f"EXPORT approved_receipts.csv rows={len(rows)} total={total:.2f}")
    print("CHECK PASS: every row is approved; accounting import remains manual")


def main() -> None:
    if len(sys.argv) < 3:
        raise SystemExit("USAGE make-samples INPUT_DIR | scan INPUT_DIR WORK_DIR | approve WORK_DIR CORRECTIONS.csv")
    command = sys.argv[1]
    if command == "make-samples" and len(sys.argv) == 3:
        make_samples(Path(sys.argv[2]))
    elif command == "scan" and len(sys.argv) == 4:
        scan(Path(sys.argv[2]), Path(sys.argv[3]))
    elif command == "approve" and len(sys.argv) == 4:
        approve(Path(sys.argv[2]), Path(sys.argv[3]))
    else:
        raise SystemExit("USAGE make-samples INPUT_DIR | scan INPUT_DIR WORK_DIR | approve WORK_DIR CORRECTIONS.csv")


if __name__ == "__main__":
    main()
