"""run.py — Lab 04 demo (offline). Generates a skewed synthetic cheque, runs the
REAL OpenCV preprocessing, then exercises the Arabic numeral/words logic and the
words-vs-figures cheque control.

    python run.py            # prints results
    python run.py --save     # also writes before/after PNGs to ./out/
"""
from __future__ import annotations

import sys

import cv2

from arabic import (arabic_words_to_number, normalize_digits, parse_figure,
                    words_match_figures)
from preprocess import deskew, estimate_skew_angle, preprocess_pipeline, to_grayscale
from synth import CHEQUE_OCR, CHEQUE_OCR_MISMATCH, create_cheque_image


def main() -> None:
    print("=" * 66 + "\n1) OpenCV preprocessing: deskew a crooked scan\n" + "=" * 66)
    skewed = create_cheque_image(angle=8.0)
    before = estimate_skew_angle(to_grayscale(skewed))
    deskewed, applied = deskew(skewed)
    after = estimate_skew_angle(to_grayscale(deskewed))
    print(f"  estimated skew before : {before:+.2f} deg")
    print(f"  rotation applied      : {applied:+.2f} deg")
    print(f"  residual skew after   : {after:+.2f} deg  (closer to 0 = straightened)")

    print("\n" + "=" * 66 + "\n2) Arabic numerals + amount-in-words\n" + "=" * 66)
    print(f"  normalize '١٢٥٠'         -> {normalize_digits('١٢٥٠')}")
    print(f"  parse_figure '١٬٢٥٠٫٠٠'  -> {parse_figure('١٬٢٥٠٫٠٠')}")
    print(f"  words 'ألف ومئتان وخمسون' -> {arabic_words_to_number('ألف ومئتان وخمسون')}")

    print("\n" + "=" * 66 + "\n3) Cheque control: amount-in-words vs amount-in-figures\n" + "=" * 66)
    ok = words_match_figures(CHEQUE_OCR["amount_words_ar"], CHEQUE_OCR["amount_figures"], lang="ar")
    bad = words_match_figures(CHEQUE_OCR_MISMATCH["amount_words_ar"],
                              CHEQUE_OCR_MISMATCH["amount_figures"], lang="ar")
    print(f"  clean cheque  words==figures? {ok}   (1250 vs 1250.00)")
    print(f"  fraud cheque  words==figures? {bad}  (1250 vs 1350.00) -> HUMAN REVIEW")

    if "--save" in sys.argv:
        import os
        os.makedirs("out", exist_ok=True)
        cv2.imwrite("out/cheque_skewed.png", skewed)
        cv2.imwrite("out/cheque_deskewed.png", deskewed)
        cv2.imwrite("out/cheque_binarized.png", preprocess_pipeline(skewed))
        print("\n  wrote out/cheque_skewed.png, out/cheque_deskewed.png, out/cheque_binarized.png")


if __name__ == "__main__":
    main()
