<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt');

// --- Debug Logging ---
$log_file = __DIR__ . '/translate_log.txt';
file_put_contents($log_file, "--- New Translation Request ---
", FILE_APPEND);

function write_log($message) {
    global $log_file;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($log_file, "[{$timestamp}] " . print_r($message, true) . "\n", FILE_APPEND);
}
// --- End Debug Logging ---

require_once __DIR__ . '/ai/LocalAIApi.php';

function json_response($status, $message, $data = null) {
    write_log("Sending JSON response: Status: {$status}, Message: {$message}");
    header('Content-Type: application/json');
    echo json_encode([
        'status' => $status,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

write_log("Request method: " . $_SERVER['REQUEST_METHOD']);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response('error', 'Invalid request method.');
}

write_log("POST data: " . json_encode($_POST));
if (!isset($_POST['file_path']) || !isset($_POST['source-lang']) || !isset($_POST['target-lang'])) {
    json_response('error', 'Missing required parameters.');
}

$file_path = $_POST['file_path'];
$source_lang = $_POST['source-lang'];
$target_lang = $_POST['target-lang'];

$url_path = parse_url($file_path, PHP_URL_PATH);
$full_path = __DIR__ . $url_path;
write_log("Full file path: {$full_path}");

if (!file_exists($full_path)) {
    json_response('error', 'File not found.');
}

try {
    // Step 1: Perform OCR on the image
    write_log("Performing OCR on file: {$full_path}");
    // Use escapeshellarg to prevent command injection vulnerabilities
    $escaped_path = escapeshellarg($full_path);
    $ocr_command = "tesseract {$escaped_path} stdout";
    write_log("Executing OCR command: {$ocr_command}");
    
    // Execute the command and capture the output
    $extracted_text = shell_exec($ocr_command);
    write_log("OCR raw output: " . $extracted_text);

    if ($extracted_text === null || trim($extracted_text) === '') {
        json_response('error', 'OCR failed or no text was found in the image.');
    }
    
    $extracted_text = trim($extracted_text);
    write_log("Extracted text (trimmed): " . $extracted_text);

    // Step 2: Translate the extracted text
    write_log("Sending extracted text to AI for translation...");
    
    $prompt = "Translate the following text from {$source_lang} to {$target_lang}:\n\n{$extracted_text}";
    
    $payload = [
        'input' => [
            [
                'role' => 'user',
                'content' => $prompt
            ]
        ]
    ];

    write_log("AI request payload: " . json_encode($payload, JSON_PRETTY_PRINT));
    $resp = LocalAIApi::createResponse($payload);
    write_log("Received response from AI API: " . json_encode($resp, JSON_PRETTY_PRINT));

    if (!empty($resp['success'])) {
        $translated_text = LocalAIApi::extractText($resp);
        if ($translated_text === '') {
            $decoded = LocalAIApi::decodeJsonFromResponse($resp);
            $error_details = $decoded ? json_encode($decoded, JSON_PRETTY_PRINT) : 'AI returned an empty or invalid response.';
            json_response('error', 'AI translation failed. Details: ' . $error_details);
        } else {
            json_response('success', 'Translation successful!', ['translatedText' => $translated_text, 'extractedText' => $extracted_text]);
        }
    } else {
        $error_message = $resp['error'] ?? 'Unknown AI error.';
        json_response('error', 'AI translation failed: ' . $error_message);
    }

} catch (Exception $e) {
    write_log("An exception occurred: " . $e->getMessage());
    write_log("Stack trace: " . $e->getTraceAsString());
    json_response('error', 'An unexpected error occurred: ' . $e->getMessage());
}
?>