#!/usr/bin/env perl
use 5.014;
use strict;
use warnings;
use Getopt::Long qw(GetOptions);
use JSON::PP ();
use Text::OCR::Benchmark;

our $VERSION = '1.00';

my ($opt_json, $opt_arabic, $opt_hocr, $opt_iou, $opt_help, $opt_ver);
$opt_iou = 0.5;

GetOptions(
    'json'           => \$opt_json,
    'arabic'         => \$opt_arabic,
    'hocr'           => \$opt_hocr,
    'iou=f'          => \$opt_iou,
    'help|h'         => \$opt_help,
    'version|v'      => \$opt_ver,
) or die "Usage: ocr-benchmark [--json] [--arabic] [--hocr --iou 0.5] <ref_file> <hyp_file>\n";

if ($opt_ver) {
    print "ocr-benchmark v$VERSION (Text::OCR::Benchmark)\n";
    exit 0;
}

if ($opt_help || @ARGV < 2) {
    print <<"USAGE";
Usage: ocr-benchmark [OPTIONS] <ground_truth_file> <ocr_output_file>

Options:
  --json         Emit evaluation metrics as structured JSON
  --arabic       Strip Arabic diacritics (harakat) and unify Alef/Yeh variants
  --hocr         Evaluate hOCR spatial word bounding-box IoU & F1 instead of raw text
  --iou <float>  IoU threshold for --hocr true-positive matching (default: 0.5)
  --version, -v  Print version
  --help, -h     Show this help message
USAGE
    exit($opt_help ? 0 : 1);
}

my ($gt_path, $hyp_path) = @ARGV;
my $gt_text  = _slurp_utf8($gt_path);
my $hyp_text = _slurp_utf8($hyp_path);

my $bench = Text::OCR::Benchmark->new(
    strip_arabic_diac => $opt_arabic ? 1 : 0,
    unify_arabic_alef => $opt_arabic ? 1 : 0,
);

if ($opt_hocr) {
    my $res = $bench->evaluate_hocr($gt_text, $hyp_text, iou_threshold => $opt_iou);
    if ($opt_json) {
        print JSON::PP->new->utf8->canonical->pretty->encode($res);
    }
    else {
        printf "hOCR Boxes (GT / Pred): %d / %d\n", $res->{gt_count}, $res->{pred_count};
        printf "Precision: %.4f | Recall: %.4f | F1: %.4f | Mean TP IoU: %.4f\n",
            $res->{precision}, $res->{recall}, $res->{f1}, $res->{mean_tp_iou};
    }
    exit 0;
}

my $res = $bench->evaluate($gt_text, $hyp_text);
if ($opt_json) {
    print JSON::PP->new->utf8->canonical->pretty->encode($res);
    exit 0;
}

printf "Character Error Rate (CER): %.6f (Accuracy: %.2f%%)\n",
    $res->{cer}, $res->{char_accuracy_pct};
printf "Word Error Rate (WER):      %.6f (Accuracy: %.2f%%)\n",
    $res->{wer}, $res->{word_accuracy_pct};
printf "Char Edits (S / I / D):     %d / %d / %d (of %d chars)\n",
    $res->{char_edits}{substitutions},
    $res->{char_edits}{insertions},
    $res->{char_edits}{deletions},
    $res->{reference_chars};

exit 0;

sub _slurp_utf8 {
    my ($p) = @_;
    open my $fh, '<:encoding(UTF-8)', $p or die "Cannot read '$p': $!\n";
    local $/;
    my $data = <$fh>;
    close $fh;
    return $data;
}

__END__

=head1 NAME

ocr-benchmark - Command-line OCR Character Error Rate (CER), Word Error Rate (WER), and hOCR IoU evaluator

=head1 SYNOPSIS

    ocr-benchmark ground_truth.txt tesseract_out.txt
    ocr-benchmark --arabic --json gt_ar.txt ocr_ar.txt
    ocr-benchmark --hocr --iou 0.5 page_gt.hocr page_pred.hocr

=head1 AUTHOR

Islam Ayoub (UTILVO) E<lt>info@utilvo.comE<gt>

=cut
