<?php

namespace App\Services\OCR\Drivers;

use App\Services\OCR\OCRInterface;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ExternalOCRDriver implements OCRInterface
{
    protected $url;
    protected $timeout;

    public function __construct(array $config)
    {
        $this->url = $config['url'];
        $this->timeout = $config['timeout'];
    }

    public function recognize(string $imagePath, array $options = []): array
    {
        try {
            if (!file_exists($imagePath)) {
                throw new \Exception('Image file not found: ' . $imagePath);
            }

            $multipart = [
                [
                    'name' => 'image',
                    'contents' => fopen($imagePath, 'r'),
                    'filename' => basename($imagePath),
                ],
            ];

            if (isset($options['student_id'])) {
                $multipart[] = [
                    'name' => 'student_id',
                    'contents' => $options['student_id'],
                ];
            }

            $response = Http::timeout($this->timeout)
                ->asMultipart()
                ->post($this->url . '/ocr/analyze-paper', $multipart);

            if ($response->failed()) {
                throw new \Exception('External OCR service failed: ' . $response->body());
            }

            return $response->json();

        } catch (\Exception $e) {
            Log::error('External OCR Error', [
                'message' => $e->getMessage(),
            ]);
            throw $e;
        }
    }
}
