<?php

function translate_libre($text, $sourceLang = 'en', $targetLang = 'de') {
	if (empty($text)) return '';

	$url = 'http://host.docker.internal:5001/translate';

	$data = json_encode([
		'q' => $text,
		'source' => $sourceLang,
		'target' => $targetLang,
		'format' => 'text'
	]);

	$ch = curl_init($url);
	curl_setopt_array($ch, [
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_POST => true,
		CURLOPT_POSTFIELDS => $data,
		CURLOPT_HTTPHEADER => [
			'Content-Type: application/json'
		],
		CURLOPT_TIMEOUT => 5
	]);

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

	if ($httpCode !== 200 || !$response) {
		error_log("LibreTranslate Fehler ($httpCode): $response");
		return $text;
	}

	$result = json_decode($response, true);
	return $result['translatedText'] ?? $text;
}
