<?php

namespace App\Services\OCR;

class AnswerParser
{
    /**
     * Parse answer letters from OCR text
     * Expected format: "A\nB\nC\nD" or "A B C D" or similar
     * 
     * @param string $text OCR recognized text from answer area
     * @return array Array of answer letters, indexed by question number
     */
    public function parseAnswers(string $text): array
    {
        $answers = [];
        
        // Remove extra whitespace and normalize
        $text = trim($text);
        
        // Split by common delimiters: newline, backslash, space, comma
        $parts = preg_split('/[\n\r\\\\\s,]+/', $text);
        
        $questionNumber = 1;
        foreach ($parts as $part) {
            $part = trim($part);
            
            // Check if it's a valid answer letter (A, B, C, D, or lowercase)
            if (preg_match('/^[A-Da-d]$/', $part)) {
                $answers[$questionNumber] = strtoupper($part);
                $questionNumber++;
            }
        }
        
        \Log::info('Parsed answers from OCR text', [
            'raw_text' => $text,
            'parsed_answers' => $answers,
            'count' => count($answers)
        ]);
        
        return $answers;
    }

    /**
     * Parse a single answer letter from OCR text
     * 
     * @param string $text OCR text from a single question's answer area
     * @return string|null The answer letter (A/B/C/D) or null if not found
     */
    public function parseSingleAnswer(string $text): ?string
    {
        $text = trim($text);
        
        // Look for A, B, C, or D (case insensitive)
        if (preg_match('/[A-Da-d]/', $text, $matches)) {
            return strtoupper($matches[0]);
        }
        
        return null;
    }

    /**
     * Match parsed answers to questions
     * 
     * @param array $questions Array of question data
     * @param array $answers Array of answers indexed by question number
     * @return array Updated questions with student_answer filled
     */
    public function matchAnswersToQuestions(array $questions, array $answers): array
    {
        foreach ($questions as &$question) {
            $questionNumber = $question['question_number'];
            if (isset($answers[$questionNumber])) {
                $question['student_answer'] = $answers[$questionNumber];
            }
        }
        
        return $questions;
    }
}
