<?php
// execute_OCR.php
header('Content-Type: application/json');

$debugLogFile = __DIR__ . '/execute_OCR_debug.log';
$start = microtime(true); 

function writeLog($message) {
    global $debugLogFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($debugLogFile, "[$timestamp] $message\n", FILE_APPEND);
}

writeLog("--- NEUER REQUEST ---");

// 1. Initialer Check der Umgebung
if (!file_exists(__DIR__ . '/api_keys.php')) {
    writeLog("KRITISCH: api_keys.php existiert nicht!");
    echo json_encode(['OCRExitCode' => 3, 'ErrorMessage' => 'Config fehlt']);
    exit;
}
$keys = require __DIR__ . '/api_keys.php';

$gKey = $keys['GOOGLE_API_KEY_BACKEND'] ?? '';
$oKey = $keys['OCR_SPACE_KEY'] ?? '';
$googleStatus = !empty($gKey) ? "VORHANDEN (" . substr($gKey, 0, 4) . "...)" : "FEHLT";
writeLog("Config-Check: Google Backend Key $googleStatus | OCR.space Key " . (!empty($oKey) ? "VORHANDEN" : "FEHLT"));

// --- DER SCHALTER ---
$useOCRSpaceAsPrimary = true; 
// --------------------

// 2. Validierung
if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
    $err = $_FILES['photo']['error'] ?? 'Keine Datei';
    writeLog("FEHLER: Upload-Problem. PHP-Code: $err");
    echo json_encode(['OCRExitCode' => 3, 'ErrorMessage' => 'Upload-Fehler']);
    exit;
}

$imagePath = $_FILES['photo']['tmp_name'];
$ocrSuccess = false;
$parsedText = '';
$usedAPI = 'NONE';

// 3. VERSUCH 1: OCR.space (MIT ERWEITERTEM FEHLER-LOGGING)
if ($useOCRSpaceAsPrimary && !empty($oKey)) {
    writeLog("Step 1: Starte OCR.space (Engine 2)");
    
    $postData = [
        'apikey'    => $oKey,
        'language'  => 'ger',
        'OCREngine' => '2',
        'file'      => new CURLFile($imagePath, $_FILES['photo']['type'], $_FILES['photo']['name'])
    ];

    $ch = curl_init('https://api.ocr.space/parse/image');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 3); 

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr = curl_error($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    
    if ($httpCode === 200 && isset($data['ParsedResults'][0]['ParsedText']) && !empty($data['ParsedResults'][0]['ParsedText'])) {
        $parsedText = $data['ParsedResults'][0]['ParsedText'];
        $ocrSuccess = true;
        $usedAPI = 'OCR.SPACE';
        writeLog("OCR.space ERFOLG.");
    } else {
        // HIER: Extraktion des spezifischen OCR.space Fehlercodes
        $ocrErrorCode = "";
        if (isset($data['OCRExitCode'])) {
            $ocrErrorCode = "[ExitCode: " . $data['OCRExitCode'] . "] ";
        }
        if (isset($data['ErrorMessage'])) {
            // Falls ErrorMessage ein Array ist (kommt vor), in String umwandeln
            $msg = is_array($data['ErrorMessage']) ? implode(", ", $data['ErrorMessage']) : $data['ErrorMessage'];
            $ocrErrorCode .= "Info: " . $msg;
        }

        $finalMsg = $curlErr ?: ($ocrErrorCode ?: 'Unbekannter Fehler');
        writeLog("OCR.space FAIL - HTTP $httpCode | $finalMsg");
    }
}

// 4. FALLBACK: Google Vision
if (!$ocrSuccess) {
    writeLog("Step 2: Schalte um auf Google Vision");
    
    if (empty($gKey)) {
        writeLog("ABBRUCH: Google API Key ist leer!");
    } else {
        $googleUrl = "https://vision.googleapis.com/v1/images:annotate?key=" . $gKey;
        $imageData = base64_encode(file_get_contents($imagePath));
        $googleRequest = json_encode([
            "requests" => [[
                "image" => ["content" => $imageData],
                "features" => [["type" => "TEXT_DETECTION"]]
            ]]
        ]);

        $gh = curl_init($googleUrl);
        curl_setopt($gh, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($gh, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($gh, CURLOPT_POSTFIELDS, $googleRequest);
        curl_setopt($gh, CURLOPT_TIMEOUT, 10);
        
        $gResponse = curl_exec($gh);
        $gHttpCode = curl_getinfo($gh, CURLINFO_HTTP_CODE);
        curl_close($gh);
        
        $gData = json_decode($gResponse, true);
        $parsedText = $gData['responses'][0]['fullTextAnnotation']['text'] ?? '';

        if ($gHttpCode === 200 && !empty($parsedText)) {
            $ocrSuccess = true;
            $usedAPI = 'GOOGLE_VISION';
            writeLog("Google Vision ERFOLG.");
        } else {
            writeLog("Google Vision FAIL. HTTP: $gHttpCode");
        }
    }
}

// 5. Output
$diff = round(microtime(true) - $start, 2);
echo json_encode([
    'ParsedResults' => [['ParsedText' => $parsedText]],
    'OCRExitCode' => $ocrSuccess ? 1 : 3,
    'UsedAPI' => $usedAPI,
    'Duration' => $diff
]);

writeLog("--- ENDE (Dauer: {$diff}s) ---");