<?php

/**
 * Aggregate every locale/<iso>/*.po into a single locale/<iso>/base.mo.
 *
 * JTL loads plugin translations from the compiled base.mo (gettext), NOT from
 * the .po sources — so edited/added .po strings stay invisible until this runs.
 * Replaces the old (lost) PhpStorm File Watcher. Run inside the shop container:
 *
 *     make locale
 */

declare(strict_types=1);

use Gettext\Generator\MoGenerator;
use Gettext\Loader\PoLoader;

$autoload = '/var/www/html/includes/vendor/autoload.php';
if (!\is_file($autoload)) {
    \fwrite(\STDERR, "shop autoload not found at $autoload — run inside the jtlshop container (make locale)\n");
    exit(1);
}
require $autoload;

$localeRoot = \dirname(__DIR__) . '/locale';
$built      = 0;

foreach (\glob($localeRoot . '/*', \GLOB_ONLYDIR) ?: [] as $dir) {
    $poFiles = \glob($dir . '/*.po') ?: [];
    if ($poFiles === []) {
        continue;
    }
    \sort($poFiles);

    $merged = null;
    foreach ($poFiles as $po) {
        $translations = (new PoLoader())->loadFile($po);
        $merged       = $merged === null ? $translations : $merged->mergeWith($translations);
    }

    (new MoGenerator())->generateFile($merged, $dir . '/base.mo');
    \printf(
        "%s/base.mo <- %d po file(s), %d strings\n",
        \basename($dir),
        \count($poFiles),
        \count($merged->getTranslations())
    );
    $built++;
}

if ($built === 0) {
    \fwrite(\STDERR, "no locale dirs with .po files under $localeRoot\n");
    exit(1);
}
