<?php

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

$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Models\OCRRecord;
use App\Services\OCRService;

// Get record IDs from command line or use defaults
$recordIds = $argv[1] ?? '4,5';
$ids = explode(',', $recordIds);

echo "Processing OCR records: " . implode(', ', $ids) . "\n\n";

$ocrService = app(OCRService::class);

foreach ($ids as $id) {
    $record = OCRRecord::find(trim($id));
    
    if (!$record) {
        echo "❌ Record #{$id} not found\n";
        continue;
    }
    
    echo "📄 Processing Record #{$record->id}...\n";
    echo "   Status: {$record->status}\n";
    echo "   File: {$record->image_filename}\n";
    
    try {
        // Call the protected method via reflection
        $reflection = new ReflectionClass($ocrService);
        $method = $reflection->getMethod('dispatchToOcrService');
        $method->setAccessible(true);
        $method->invoke($ocrService, $record);
        
        $record->refresh();
        
        echo "   ✅ Completed! Questions extracted: {$record->total_questions}\n";
        
        // Show first question
        $firstQuestion = $record->questions()->first();
        if ($firstQuestion) {
            echo "   First question: " . substr($firstQuestion->question_text, 0, 60) . "...\n";
        }
        
    } catch (\Exception $e) {
        echo "   ❌ Error: " . $e->getMessage() . "\n";
    }
    
    echo "\n";
}

echo "✨ Batch processing complete!\n";
