<?php
// Usage: php scripts/populate_sl_translations.php [in-file] [out-file]
// Default input: storage/app/translations_missing_admin.csv
// This script will call LibreTranslate (https://libretranslate.com) to translate
// an English guess of each key into Slovenian and update the CSV's suggested_sl column.

$root = dirname(__DIR__);
$in = $argv[1] ?? $root . '/storage/app/translations_missing_admin.csv';
$out = $argv[2] ?? $in; // overwrite by default

if (!file_exists($in)) {
    echo "Input CSV not found: $in\n";
    exit(1);
}

$backup = $in . '.bak.' . date('YmdHis');
copy($in, $backup);
echo "Backup written to: $backup\n";

$rows = [];
$fh = fopen($in, 'r');
$header = fgetcsv($fh);
if ($header === false) {
    echo "Empty CSV\n";
    exit(1);
}

while (($data = fgetcsv($fh)) !== false) {
    $rows[] = $data;
}
fclose($fh);

$libreUrl = 'https://libretranslate.com/translate';

function translateText($text, $url)
{
    $payload = json_encode([
        'q' => $text,
        'source' => 'en',
        'target' => 'sl',
        'format' => 'text'
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $resp = curl_exec($ch);
    $err = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err) {
        throw new Exception('Curl error: ' . $err);
    }
    if ($code < 200 || $code >= 300) {
        throw new Exception('HTTP ' . $code . ' response: ' . $resp);
    }

    $json = json_decode($resp, true);
    return $json['translatedText'] ?? null;
}

echo "Processing " . count($rows) . " rows...\n";

$i = 0;
foreach ($rows as &$r) {
    $i++;
    // CSV columns: file,keycode,suggested_sl,suggested_en,placeholder
    $file = $r[0] ?? '';
    $keycode = $r[1] ?? '';
    $s_sl = $r[2] ?? '';
    $s_en = $r[3] ?? '';

    if (trim($s_sl) !== '') {
        // already populated
        continue;
    }

    // Build an English humanized guess from keycode if suggested_en is empty
    if (trim($s_en) !== '') {
        $source = $s_en;
    } else {
        $source = strtolower(str_replace('_', ' ', $keycode));
        // Make it sentence-like: capitalize first letter and replace multiple spaces
        $source = preg_replace('/\s+/', ' ', $source);
        $source = ucfirst($source);
    }

    try {
        $translated = translateText($source, $libreUrl);
        if ($translated === null) {
            $translated = '';
        }
        $r[2] = $translated;
        echo "[{$i}] OK: {$keycode} -> {$translated}\n";
    } catch (\Throwable $e) {
        echo "[{$i}] WARN: {$keycode} -> " . $e->getMessage() . "\n";
        // leave blank on error
    }

    // Rate limit: sleep 0.5s
    usleep(500000);
}
unset($r);

// Write out CSV
$ofh = fopen($out, 'w');
fputcsv($ofh, $header);
foreach ($rows as $row) {
    fputcsv($ofh, $row);
}
fclose($ofh);

echo "Wrote updated CSV to: $out\n";

exit(0);
