<?php
/**
 * Add missing translations for v1.7.02 features:
 *   - Auto-translate strings button
 *   - Overwrite existing checkbox
 *   - Auto-translate description
 *   - Theme Compatibility (optional) heading
 *   - Most sites need nothing here... description
 *   - Custom Types dashboard tab
 *   - Translating… progress message
 * Usage: php add-v1702-translations.php
 */

$envFile = 'E:\\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',
];

$allStrings = [
    'Auto-translate strings',
    'Overwrite existing',
    'Auto-translate fills every language for the detected strings (your saved entries plus the site\'s WooCommerce payment titles/descriptions and checkout privacy text) using the translation engine. Review the results — save afterwards is automatic.',
    '🎨 Theme Compatibility (optional)',
    'Most sites need nothing here — page content, Elementor/Gutenberg data, and WooCommerce fields are translated automatically. This section is only for themes that store translatable text in custom meta fields. If the status below says "Standard", you can ignore it.',
    'Custom Types',
    'Translating…',
];

function translateBatch(array $strings, string $langName, string $apiKey): array|false {
    $numbered = [];
    foreach ($strings as $i => $s) {
        $numbered[] = ($i + 1) . '. ' . $s;
    }
    $list = implode("\n", $numbered);

    $prompt = "Translate the following UI strings from English to {$langName}.\n"
        . "Rules:\n"
        . "- Return ONLY the translations, one per line, numbered the same way\n"
        . "- Keep any emoji at the start of a string\n"
        . "- Keep placeholders like %s, %d, {{count}} unchanged\n"
        . "- Keep HTML tags unchanged\n"
        . "- Keep the em-dash (—) character as-is\n"
        . "- Do not add quotes around translations\n\n"
        . $list;

    $ch = curl_init('https://api.openai.com/v1/chat/completions');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
        ],
        CURLOPT_POSTFIELDS => json_encode([
            'model'    => 'gpt-4o-mini',
            'messages' => [
                ['role' => 'system', 'content' => 'You are a professional WordPress plugin translator.'],
                ['role' => 'user',   'content' => $prompt],
            ],
            'temperature' => 0.1,
        ]),
        CURLOPT_TIMEOUT => 60,
    ]);

    $response = curl_exec($ch);
    $err      = curl_error($ch);
    curl_close($ch);

    if ($err || !$response) {
        echo "  CURL ERROR: $err\n";
        return false;
    }

    $data = json_decode($response, true);
    $text = $data['choices'][0]['message']['content'] ?? '';
    if (!$text) {
        echo "  API ERROR: " . print_r($data, true) . "\n";
        return false;
    }

    $lines = explode("\n", trim($text));
    $results = [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '') continue;
        // Strip leading "N. " numbering
        $line = preg_replace('/^\d+\.\s*/', '', $line);
        $results[] = $line;
    }

    return $results;
}

function msgfmtCompile(string $poFile): void {
    $moFile = preg_replace('/\.po$/', '.mo', $poFile);
    $cmd    = 'msgfmt ' . escapeshellarg($poFile) . ' -o ' . escapeshellarg($moFile) . ' 2>&1';
    $out    = shell_exec($cmd);
    if ($out) {
        echo "  msgfmt: $out\n";
    } else {
        echo "  [OK] Compiled: " . basename($moFile) . "\n";
    }
}

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 — skipping\n\n";
        continue;
    }

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

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

    if ($translations === false) {
        echo "  ERROR: Translation failed — skipping $locale\n\n";
        continue;
    }

    $appendBlock = "\n\n# --- Added by add-v1702-translations.php (" . date('Y-m-d') . ") ---\n";
    foreach ($missing as $i => $original) {
        $translated = isset($translations[$i]) ? $translations[$i] : '';
        $escapedOrig  = addcslashes($original, '"\\');
        $escapedTrans = addcslashes($translated, '"\\');
        $appendBlock .= "\n";
        $appendBlock .= "msgid \"{$escapedOrig}\"\n";
        $appendBlock .= "msgstr \"{$escapedTrans}\"\n";
    }

    file_put_contents($poFile, $poContent . $appendBlock);
    echo "  [OK] Appended " . count($missing) . " translations\n";

    msgfmtCompile($poFile);
    echo "\n";
}

echo "Done.\n";
