<?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;

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

use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\FormRenderer;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
use Twig\Extension\ExtensionInterface;
use Twig\RuntimeLoader\FactoryRuntimeLoader;

class TwigExtensionRegistry
{
    private const PRESTASHOP_EXTENSIONS = [
        'prestashop.twig.extension.translation',
        'prestashop.twig.extension.data_formatter',
        'prestashop.twig.extension.layout',
        'prestashop.twig.extension.hook',
    ];

    private const SYMFONY_EXTENSIONS = [
        'twig.extension.trans',
        'twig.extension.assets',
        'twig.extension.routing',
        'twig.extension.form',
    ];

    public function __construct(
        private ContainerInterface $container,
        private LoggerInterface $logger,
        private ?TranslatorInterface $translator = null
    ) {
    }

    public function registerExtensions(Environment $twig): void
    {
        $this->addTranslationExtension($twig);
        $this->addFormExtension($twig);
        $this->addContainerExtensions($twig);
    }

    private function addTranslationExtension(Environment $twig): void
    {
        if ($this->translator === null || !class_exists(TranslationExtension::class)) {
            $this->logger->debug('Translation extension class not available');

            return;
        }

        try {
            $twig->addExtension(new TranslationExtension($this->translator));
        } catch (\Exception $exception) {
            $this->logger->debug('Failed to add translation extension: ' . $exception->getMessage());
        }
    }

    private function addFormExtension(Environment $twig): void
    {
        if (!class_exists(TwigRendererEngine::class) || !class_exists(FormExtension::class)) {
            $this->logger->debug('Form extension classes not available');

            return;
        }

        try {
            $formEngine = new TwigRendererEngine(['form_div_layout.html.twig'], $twig);
            $twig->addRuntimeLoader(new FactoryRuntimeLoader([
                FormRenderer::class => fn () => new FormRenderer($formEngine),
            ]));
            $twig->addExtension(new FormExtension());
            $this->logger->debug('Added Symfony Form extension');
        } catch (\Exception $exception) {
            $this->logger->warning('Failed to add Form extension: ' . $exception->getMessage());
        }
    }

    private function addContainerExtensions(Environment $twig): void
    {
        $allExtensions = array_merge(self::PRESTASHOP_EXTENSIONS, self::SYMFONY_EXTENSIONS);

        foreach ($allExtensions as $extensionService) {
            $this->addExtensionIfAvailable($twig, $extensionService);
        }
    }

    private function addExtensionIfAvailable(Environment $twig, string $serviceId): void
    {
        if (!$this->container->has($serviceId)) {
            $this->logger->debug(sprintf('Twig extension service "%s" not found', $serviceId));

            return;
        }

        try {
            $extension = $this->container->get($serviceId);

            if (!$extension instanceof ExtensionInterface) {
                $this->logger->debug(sprintf('Service "%s" is not a Twig extension', $serviceId));

                return;
            }

            if ($twig->hasExtension(get_class($extension))) {
                return;
            }

            $twig->addExtension($extension);
            $this->logger->debug(sprintf('Added Twig extension: %s', get_class($extension)));
        } catch (\Exception $exception) {
            $this->logger->warning(sprintf(
                'Failed to add extension "%s": %s',
                $serviceId,
                $exception->getMessage()
            ));
        }
    }
}
