<?php

namespace routes;

use classes\authentication;
use classes\image_processor;
use classes\licenseplaterecognizer;
use classes\openai;
use classes\response;
use classes\router;
use classes\upload_store;
use Exception;
use objects\logs_o;
use traits\route_t;

class moduleScannerRoute
{
    use route_t;

    public function run(): void
    {
        global /** @var response $response */
        $router, $response;
        /** Modules > Scanner > License Plate Recognition > POST */
        $this->post('/modules/scanner/lpr', function () {
            global $response;
            self::requireParameters(['base64_image']);
            $base64_image = self::getParameter('base64_image');
            //self::requirePermission('modules_scanner_lpr');
            if (empty($base64_image)) {
                $response->error('Base64 image is required.');}
            $uploads = new upload_store();
            $object_name = $uploads->storeTempImageFromBase64(
                $base64_image
            );
            //echo $object_name;
            //echo "License Plate Recognition result:\n";
            // Uncomment the line below to use the actual license plate recognizer.
            $lpr_result = (new licenseplaterecognizer())->licenseplaterecognizer($base64_image);
            if ($lpr_result['success']) {
                // Set the LICENSE_PLATE_NUMBER to uppercase and remove spaces.
                $lpr_result['license_plate_number'] = strtoupper(str_replace(' ', '', $lpr_result['license_plate_number']));
                // Make sure the scanned plate is more than 3 characters long.
                $scannedPlateIsTooShort = strlen($lpr_result['license_plate_number']) <= 3;
                // If the confidence is below 90%, consider it a failure.
                if (isset($lpr_result['confidence']) && $lpr_result['confidence'] < 0.9 && !$scannedPlateIsTooShort) {
                    throw new Exception('License plate recognition confidence too low. Score: ' . $lpr_result['confidence'] . ' Plate: ' . $lpr_result['license_plate_number'] . ' Raw: ' . json_encode($lpr_result['raw_response']));
                }
                // Success
                $response->success(['success' => true, 'license_plate_number' => $lpr_result['license_plate_number']]);
            } else {
                throw new Exception('License plate extraction failed.');
                //$response->error($lpr_result['message'] ?? 'License plate recognition failed.', $lpr_result);
            }
            exit;
            // For future use with OpenAI.
            $openai = new openai();
            $registration_numbers_debug = [
                'EC21233',
                'EC21234',
                'EC21235',
            ];
            $random_index = rand(0, count($registration_numbers_debug) - 1);
            $object_name = $registration_numbers_debug[$random_index];
            // Attempt to recognize the license plate number from the image.

            //Debug: TODO: Remove this.
            $response->success(['success' => true, 'license_plate_number' => $object_name]);
            $response->success($openai->lpr($object_name));
        },
            [
                'modules_scanner_lpr' => 'License Plate Recognition',
            ]
        );
    }
}