<?php
declare(strict_types=1);

namespace App\Core\I18n;

use RuntimeException;

final class Translator
{
    /** @var array<string, mixed> */
    private array $messages;

    public function __construct(
        private readonly string $langPath,
        private readonly string $locale = 'pl'
    ) {
        $this->messages = $this->load($this->locale);
    }

    /**
     * @param array<string, scalar> $replace
     */
    public function get(string $key, array $replace = []): string
    {
        $value = $this->resolve($key);
        if (!is_string($value) || $value === '') {
            $value = $key;
        }

        foreach ($replace as $name => $replacement) {
            $value = str_replace(':' . $name, (string) $replacement, $value);
        }

        return $value;
    }

    /**
     * @return array<string, mixed>
     */
    private function load(string $locale): array
    {
        $file = rtrim($this->langPath, '/\\') . '/' . $locale . '.php';
        if (!is_file($file)) {
            throw new RuntimeException('Translation file not found: ' . $file);
        }

        $messages = require $file;
        if (!is_array($messages)) {
            throw new RuntimeException('Translation file must return array: ' . $file);
        }

        return $messages;
    }

    private function resolve(string $key): mixed
    {
        $segments = explode('.', $key);
        $value = $this->messages;

        foreach ($segments as $segment) {
            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return null;
            }

            $value = $value[$segment];
        }

        return $value;
    }
}
