<?php
/**
 * Add missing translations for:
 *   - Exclude Paths from Language Routing (Settings → Language Routing)
 *   - Retranslate Product Short Descriptions tool (Settings → WooCommerce)
 *   - Force re-translate checkbox
 *   - Mini-cart checklist section strings (if any)
 *
 * Usage: php add-minicart-translations.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 introduced in v1.6.4 / v1.6.5
$allStrings = [
    // Settings → Language Routing: Exclude Paths
    'Exclude Paths from Language Routing',
    'One path or token per line. Matching URLs are never given a language prefix and never redirected — useful for plugin API/rewrite endpoints, webhooks, and callbacks. Example: enter "wcsag-api" to exclude /wcsag-api/... requests.',
    'REST API (/wp-json/), admin-ajax, WooCommerce API (/wc-api/), feeds, login and XML-RPC are always excluded automatically.',

    // Settings → WooCommerce: Retranslate Short Descriptions tool
    'Retranslate Product Short Descriptions',
    'Re-translates the short description (excerpt) for all translated products. Use this if product short descriptions still appear in the source language. Safe to re-run: already-translated products are skipped unless their source text changed, or you tick "Force re-translate".',
    'Retranslate Short Descriptions',
    'Force re-translate (ignore already-translated)',
];

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-minicart-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";
}

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

// ============================================================
// Helper functions
// ============================================================

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, %1\$s, %2\$d exactly as-is
3. Preserve all HTML tags exactly as-is
4. Keep brand names untranslated: Polylang, WPML, Elementor, OpenAI, WordPress, WooCommerce, Yoast SEO, Rank Math, MeepTech, REST API, XML-RPC, admin-ajax
5. Preserve technical tokens like /wp-json/, /wc-api/ exactly as-is (keep slashes and hyphens)
6. Use formal/polite form (Sie/Vous/Usted/Lei etc.) for UI text
7. The em dash — should be translated naturally (use a dash or the target language equivalent)

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'] ?? '';

    // Strip markdown code block if present
    $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 . '"';
}
