<?php

declare(strict_types=1);

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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$text = trim($input['text'] ?? '');
$targetLang = trim($input['target_lang'] ?? '');

if (!$text || !$targetLang) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing text or target_lang']);
    exit;
}

$response = LocalAIApi::createResponse([
    'input' => [
        ['role' => 'system', 'content' => 'You are a helpful translator. Translate the user input accurately. Output only the translated text.'],
        ['role' => 'user', 'content' => "Translate the following text to {$targetLang}: \"{$text}\""],
    ],
], [
    'poll_interval' => 2,
    'poll_timeout' => 30
]);

if (empty($response['success'])) {
    http_response_code(500);
    error_log("AI Translation Failed: " . json_encode($response));
    echo json_encode(['error' => 'AI translation failed', 'details' => $response['error'] ?? 'Unknown error']);
    exit;
}

$translatedText = LocalAIApi::extractText($response);

// Clean up any accidental quotes if the model adds them despite instructions
$translatedText = trim($translatedText, " 	


'" );

echo json_encode(['translation' => $translatedText]);
