<?php

use App\Services\OCRDataParser;
use App\Models\PaperQuestion;
use App\Models\OCRRecord;

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

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

$recordId = 4;
$ocrRecord = OCRRecord::find($recordId);

$rawOcrData = \Illuminate\Support\Facades\DB::table('ocr_raw_data')
    ->where('ocr_record_id', $recordId)
    ->value('raw_response');

if (!$rawOcrData) {
    echo "No raw data found for record {$recordId}\n";
    exit;
}

$rawOcrData = json_decode($rawOcrData, true);
$paperQuestions = PaperQuestion::where('paper_id', $ocrRecord->analysis_id)
    ->orderBy('question_number')
    ->get();

$parser = new OCRDataParser();

echo "Testing matchWithSystemPaper with improved logic...\n";
$results = $parser->matchWithSystemPaper($rawOcrData, $paperQuestions);

foreach ($results as $qNum => $result) {
    echo "Question {$qNum}:\n";
    echo "  Y-Range: {$result['coordinates']['y_min']} - {$result['coordinates']['y_max']}\n";
    echo "  Answer: " . mb_substr($result['student_answer'], 0, 50) . "...\n";
}
