<?php
/**
 * Add missing translations for the String Translations feature (v1.6.13).
 * Also adds translations for Translate All batch-loop progress strings if missing.
 * Usage: php add-string-translations-ui.php
 */

$envFile = 'C:\\Users\\Andrei\\repos\\meeptech\\.env.local';
$envContent = file_get_contents($envFile);
preg_match('/OPENAI_API_KEY=(.+)/', $envContent, $m);
$apiKey = trim($m[1] ?? '');
if (!$apiKey) { die("No API key found in $envFile\n"); }

$langDir = __DIR__;
$domain = 'ai-translator-for-elementor-and-polylang';

$languages = [
    'de_DE' => 'German',
    'es_ES' => 'Spanish',
    'fr_FR' => 'French',
    'it_IT' => 'Italian',
    'nl_NL' => 'Dutch',
    'pl_PL' => 'Polish',
    'pt_BR' => 'Brazilian Portuguese',
    'ru_RU' => 'Russian',
    'uk'    => 'Ukrainian',
];

// New strings for the String Translations UI and related features
$allStrings = [
    // String Translations section heading / description
    'String Translations',
    'Translate interface strings that aren\'t covered by automatic translation — payment method titles/descriptions, the checkout privacy notice, and text from other plugins. Enter the exact source text on the left, then its translation for each language. Leave a language blank to keep the original.',
    // Table header
    'Source text',
    // Row placeholder
    'Original text…',
    // Row remove button tooltip
    'Remove',
    // Add-row button
    '+ Add string',
];

foreach ($languages as $locale => $langName) {
    $poFile = $langDir . "/{$domain}-{$locale}.po";
    if (!file_exists($poFile)) {
        echo "SKIP: $poFile not found\n";
        continue;
    }

    echo "=== Processing: $langName ($locale) ===\n";
    $poContent = file_get_contents($poFile);

    $missing = [];
    foreach ($allStrings as $str) {
        $escaped = addcslashes($str, '"');
        if (strpos($poContent, 'msgid "' . $escaped . '"') === false) {
            $missing[] = $str;
        }
    }

    if (empty($missing)) {
        echo "  No missing strings!\n\n";
        continue;
    }

    echo "  Missing: " . count($missing) . " strings\n";
    echo "  Translating...\n";

    $result = translateBatch($missing, $langName, $apiKey);

    if ($result === false) {
        echo "  ERROR: Translation failed\n\n";
        continue;
    }

    $appendBlock = "\n\n# --- Added by add-string-translations-ui.php (" . date('Y-m-d') . ") ---\n";
    foreach ($missing as $i => $original) {
        if (isset($result[$i])) {
            $appendBlock .= "\n";
            $appendBlock .= formatPoEntry($original, $result[$i]);
        }
    }

    file_put_contents($poFile, $poContent . $appendBlock);
    echo "  Appended " . count($result) . " translations to $poFile\n\n";
}

echo "=== Compiling .mo files ===\n";
require_once __DIR__ . '/generate-mo-files.php';
echo "\nDone!\n";

// ============================================================
function translateBatch(array $strings, string $targetLang, string $apiKey): array|false {
    $systemPrompt = "You are a professional translator specializing in WordPress plugin UI translations. Translate the following English strings to {$targetLang}.

RULES:
1. Return ONLY a JSON array of translated strings in the exact same order
2. Preserve all placeholders like %s, %d exactly as-is
3. Keep brand names untranslated: WordPress, WooCommerce, Elementor
4. Use formal/polite form (Sie/Vous/Usted/Lei etc.) for UI text
5. 'Source text' is a table column header for a string-override UI — translate naturally
6. 'Original text…' is a textarea placeholder — translate naturally
7. '+ Add string' is a button label — keep it short and natural
8. 'Remove' is a button tooltip to delete a table row — keep it short

Format: [\"translation 1\", \"translation 2\", ...]";

    $userPrompt = "Translate these " . count($strings) . " strings to {$targetLang}:\n\n" . json_encode($strings, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    $payload = [
        'model' => 'gpt-4o-mini',
        'messages' => [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $userPrompt],
        ],
        'temperature' => 0.2,
    ];

    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_TIMEOUT => 60,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);

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

    if ($httpCode !== 200) {
        echo "    API error ($httpCode): " . substr($response, 0, 300) . "\n";
        return false;
    }

    $data = json_decode($response, true);
    $content = $data['choices'][0]['message']['content'] ?? '';
    $content = preg_replace('/^```(?:json)?\s*/m', '', $content);
    $content = preg_replace('/\s*```\s*$/m', '', $content);
    $content = trim($content);

    $result = json_decode($content, true);
    if (!is_array($result) || count($result) !== count($strings)) {
        echo "    Parse error (expected " . count($strings) . ", got " . (is_array($result) ? count($result) : 'null') . ")\n";
        echo "    Response: " . substr($content, 0, 300) . "\n";
        return false;
    }

    return $result;
}

function formatPoEntry(string $msgid, string $msgstr): string {
    return 'msgid ' . formatPoString($msgid) . "\n"
         . 'msgstr ' . formatPoString($msgstr) . "\n";
}

function formatPoString(string $str): string {
    $str = str_replace('\\', '\\\\', $str);
    $str = str_replace('"', '\\"', $str);

    if (strpos($str, "\n") !== false) {
        $lines = explode("\n", $str);
        $result = '""' . "\n";
        foreach ($lines as $i => $line) {
            $result .= '"' . $line . ($i < count($lines) - 1 ? '\\n' : '') . '"' . "\n";
        }
        return rtrim($result);
    }

    return '"' . $str . '"';
}
