<?php

declare(strict_types=1);

namespace ApiModel\Shared\I18n;

final class Translator
{
    /** @var array<string, array<string, string>> */
    private static array $catalog = [];

    public static function normalizeLang(?string $lang): string
    {
        $value = strtolower(trim((string) $lang));
        if ($value === '') {
            return 'es';
        }
        if (str_starts_with($value, 'en')) {
            return 'en';
        }
        return 'es';
    }

    public static function get(string $key, ?string $lang = null): string
    {
        $resolved = self::normalizeLang($lang);
        $catalog = self::catalogFor($resolved);

        if (isset($catalog[$key])) {
            return $catalog[$key];
        }

        $fallback = self::catalogFor('es');
        return $fallback[$key] ?? $key;
    }

    /** @return array<string, string> */
    private static function catalogFor(string $lang): array
    {
        if (isset(self::$catalog[$lang])) {
            return self::$catalog[$lang];
        }

        $path = __DIR__ . '/' . $lang . '.php';
        if (! is_file($path)) {
            $path = __DIR__ . '/es.php';
        }

        $loaded = require $path;
        self::$catalog[$lang] = is_array($loaded) ? $loaded : [];
        return self::$catalog[$lang];
    }
}

