<?php

require_once __DIR__ . '/vendor/autoload.php';

use App\Services\OcrService;
use App\Services\VoterBoxParser;

$imagePath = __DIR__ . '/Output/voters 46.png';

echo "=== Testing Calibrated Grid Crop for voters 46.png ===\n\n";

list($imgW, $imgH) = getimagesize($imagePath);
echo "Image size: {$imgW}x{$imgH}\n\n";

// For voters 46.png, we need to skip the header section
// Estimate: Header is about 150-200px, then we have 10 rows of voter cards
$header_height = 200;  // Skip header
$footer_height = 50;   // Skip footer if any

$effective_height = $imgH - $header_height - $footer_height;
$card_height = floor($effective_height / 10);  // 10 rows
$card_width = floor($imgW / 3);  // 3 columns

echo "Calculated dimensions:\n";
echo "  Header skip: {$header_height}px\n";
echo "  Card height: {$card_height}px\n";
echo "  Card width: {$card_width}px\n\n";

$ocrService = new OcrService();
$parser = new VoterBoxParser();

// Crop the grid with proper offsets
$crops = $ocrService->cropGridImages($imagePath, 3, 10, [
    'y_offset' => $header_height,  // Skip header
    'crop_height' => $card_height,
    'crop_width' => $card_width,
    'pad_x' => 5,
    'pad_y' => 5
]);

echo "Created " . count($crops) . " crop files\n\n";

// Test OCR on first 5 cards
echo "Testing OCR on first 5 cards:\n";
foreach (array_slice($crops, 0, 5) as $idx => $crop) {
    $result = $ocrService->ocrCrops([$crop])[0];
    $parsed = $parser->parseVoterBox($result['text']);
    
    echo "\nCard {$idx} (Row {$crop['row']}, Col {$crop['col']}):\n";
    echo "  Serial: " . ($parsed['serial_number'] ?? 'NOT FOUND') . "\n";
    echo "  Voter ID: " . ($parsed['voter_id_number'] ?? 'NOT FOUND') . "\n";
    echo "  Name: " . ($parsed['name'] ?? 'NOT FOUND') . "\n";
    
    // Save first crop for manual inspection
    if ($idx == 0) {
        copy($crop['path'], __DIR__ . '/test_crop_first_card.png');
        file_put_contents(__DIR__ . '/test_crop_first_card_ocr.txt', $result['text']);
        echo "  (Saved to test_crop_first_card.png for inspection)\n";
    }
}

// Clean up crops
foreach ($crops as $crop) {
    if (file_exists($crop['path'])) {
        @unlink($crop['path']);
    }
}

echo "\nTest complete!\n";