<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Service;

use Paysera\PrestashopPayments\Dto\TranslationsData;
use Paysera\PrestashopPayments\Provider\ModulePathsProvider;
use Psr\Log\LoggerInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Translation\Dumper\DumperInterface;
use Symfony\Component\Translation\MessageCatalogue;

if (!defined('_PS_VERSION_')) {
    exit;
}

class XliffFileGenerator
{
    private const SOURCE_LANGUAGE = 'en';

    public function __construct(
        private ModulePathsProvider $modulePaths,
        private DumperInterface $xliffDumper,
        private Filesystem $filesystem,
        private LoggerInterface $logger
    ) {
    }

    public function generate(TranslationsData $translationsData): void
    {
        $translationsPath = $this->modulePaths->getTranslationsPath();

        $this->logger->debug('Starting XLIFF translation file generation', [
            'translations_path' => $translationsPath,
        ]);

        if (!is_dir($translationsPath) || !is_writable($translationsPath)) {
            $this->logger->error('Translations directory is not writable. Translation files cannot be generated.', [
                'translations_path' => $translationsPath,
            ]);

            return;
        }

        if (!$translationsData->hasLanguage(self::SOURCE_LANGUAGE)) {
            $this->logger->warning('No source language translations found, skipping generation', [
                'source_language' => self::SOURCE_LANGUAGE,
            ]);

            return;
        }

        $englishTranslations = $translationsData->getTranslations(self::SOURCE_LANGUAGE);
        $installedLanguages = \Language::getLanguages(false);

        $this->logger->debug('Found English translations and installed languages', [
            'translation_count' => count($englishTranslations),
            'language_count' => count($installedLanguages),
        ]);

        foreach ($installedLanguages as $language) {
            $locale = $language['locale'];
            $languageCode = explode('-', $locale)[0];

            $this->logger->debug('Processing language', [
                'locale' => $locale,
                'language_code' => $languageCode,
                'language_name' => $language['name'] ?? 'unknown',
            ]);

            $targetTranslations = $translationsData->hasLanguage($languageCode)
                ? $translationsData->getTranslations($languageCode)
                : $englishTranslations;

            $this->generateLanguageFile($locale, $englishTranslations, $targetTranslations);
        }

        $this->logger->debug('XLIFF translation file generation completed');
    }

    /**
     * @param array<string, string> $sourceTranslations
     * @param array<string, string> $targetTranslations
     */
    private function generateLanguageFile(
        string $locale,
        array $sourceTranslations,
        array $targetTranslations
    ): void {
        if (!$this->isValidLocale($locale)) {
            $this->logger->warning('Invalid locale format, skipping', [
                'locale' => $locale,
            ]);

            return;
        }

        $languageDir = $this->modulePaths->getTranslationsPath() . '/' . $locale;
        $this->logger->debug('Creating language directory', [
            'directory' => $languageDir,
        ]);
        $this->filesystem->mkdir($languageDir);

        $catalogue = new MessageCatalogue($locale);
        foreach ($sourceTranslations as $machineKey => $englishText) {
            $englishText = (string) $englishText;
            $targetText = (string) ($targetTranslations[$machineKey] ?? $englishText);
            $catalogue->set($englishText, $targetText, $this->getDomain());
        }

        $this->logger->debug('Dumping XLIFF file', [
            'catalogue_locale' => $locale,
            'message_count' => count($catalogue->all($this->getDomain())),
            'domain' => $this->getDomain(),
        ]);

        $this->xliffDumper->dump($catalogue, [
            'path' => $languageDir,
            'default_locale' => self::SOURCE_LANGUAGE,
            'xliff_version' => '1.2',
        ]);

        $expectedFile = $languageDir . '/' . $this->getDomain() . '.' . $locale . '.xlf';

        if ($this->filesystem->exists($expectedFile)) {
            $this->filesystem->chmod($expectedFile, 0644);
            $this->logger->debug('Translation file generated successfully', [
                'file' => $expectedFile,
                'locale' => $locale,
            ]);
        } else {
            $this->logger->error('Translation file was not generated', [
                'expected_file' => $expectedFile,
                'locale' => $locale,
            ]);
        }
    }

    private function getDomain(): string
    {
        return str_replace('.', '', \PayseraPayments::TRANSLATION_DOMAIN);
    }

    private function isValidLocale(string $locale): bool
    {
        return preg_match('/^[a-z]{2}(-[A-Z]{2})?$/', $locale) === 1;
    }
}
