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

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

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

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

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'];

$full_path = __DIR__ . '/' . $file_path;

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

try {
    $file_content = file_get_contents($full_path);
    if ($file_content === false) {
        json_response('error', 'Failed to read file content.');
    }

    $base64_image = base64_encode($file_content);
    
    if (function_exists('mime_content_type')) {
        $mime_type = mime_content_type($full_path);
    } else {
        $mime_type = 'application/octet-stream';
    }

    $resp = LocalAIApi::createResponse([
        'input' => [
            [
                'role' => 'user',
                'content' => [
                    [
                        'type' => 'text',
                        'text' => "You are an expert document translator. Please perform the following tasks:\n" \
                            . "1. **OCR Extraction:** Extract all visible text from the attached image.\n" \
                            . "2. **Translation:** Translate the extracted text from `{$source_lang}` to `{$target_lang}`.\n" \
                            . "3. **Output:** Return ONLY the translated text as a single block of plain text. Do not include any explanations, apologies, or introductory phrases. Just the translation."
                    ],
                    [
                        'type' => 'image',
                        'source' => [
                            'type' => 'base64',
                            'media_type' => $mime_type,
                            'data' => $base64_image,
                        ],
                    ],
                ],
            ],
        ],
    ]);

    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 processing failed. Details: ' . $error_details);
        } else {
            json_response('success', 'File translated successfully.', ['translatedText' => $translated_text]);
        }
    } else {
        $error_message = $resp['error'] ?? 'Unknown AI error.';
        json_response('error', 'Failed to get response from AI service: ' . $error_message);
    }

} catch (Exception $e) {
    json_response('error', 'An exception occurred: ' . $e->getMessage());
}
?>
