<?php
/**
 * Add missing translations for the Repair Translation Links tool (v1.6.7/v1.6.8).
 * Usage: php add-repair-tool-translations.php
 *
 * v1.6.8 additions:
 *  - 'All translation links are already consistent.'  (new green scan result)
 *  - 'missing links'  (renamed counter label, was 'links')
 */

$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 Repair Translation Links tool
$allStrings = [
    'Repair Translation Links',
    'Reconciles translation links so the dashboard list, language switcher, and the cart/checkout page swap all agree. Fixes translated pages that wrongly appear as their own source, and links broken by older versions. Run "Scan" first to preview, then "Repair".',
    'Scan (preview)',
    'Repair Links',
    'Repaired',
    'Would repair',
    'groups',
    'links',
    'source refs',
    'language tags',
    'Need manual review (no source link found):',
    'Conflicts:',
    'Reload the page list to see the result.',
    'Repair translation links now? This updates link data and is safe to run multiple times.',
    // v1.6.8
    'All translation links are already consistent.',
    'missing links',
];

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-repair-tool-translations.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. 'Scan (preview)' means a dry-run preview button — translate naturally
6. 'source refs', 'language tags', 'groups', 'links' are short UI counter labels — keep them concise

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 . '"';
}
