<?php

namespace App\Command;

use App\Repository\ProductRepository;
use App\Repository\OptionsRepository;
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Liip\ImagineBundle\Imagine\Data\DataManager;
use Liip\ImagineBundle\Imagine\Filter\FilterManager;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Vich\UploaderBundle\Storage\StorageInterface;

#[AsCommand(
    name: 'app:images:warmup',
    description: 'Force la régénération du cache LiipImagine pour les images du dossier /images/',
)]
class AppWarmupImagesCommand extends Command
{
    private ProductRepository $productRepository;
    private OptionsRepository $optionsRepository;
    private CacheManager $cacheManager;
    private DataManager $dataManager;
    private FilterManager $filterManager;
    private StorageInterface $storage;

    // Adaptez cette liste à vos filtres définis dans liip_imagine.yaml
    private const FILTERS = ['webp','logo','product_card','poster_hero'];

    public function __construct(
        ProductRepository $productRepository,
        OptionsRepository $optionsRepository,
        CacheManager $cacheManager,
        DataManager $dataManager,
        FilterManager $filterManager,
        StorageInterface $storage
    ) {
        parent::__construct();
        $this->productRepository = $productRepository;
        $this->optionsRepository = $optionsRepository;
        $this->cacheManager = $cacheManager;
        $this->dataManager = $dataManager;
        $this->filterManager = $filterManager;
        $this->storage = $storage;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $products = $this->productRepository->findAll();
        $options = $this->optionsRepository->findAll();

        $io->title('Régénération FORCÉE du cache LiipImagine');
        $io->note('Le cache existant sera supprimé avant chaque génération.');

        $io->section('Produits');
        $this->processCollection($products, 'imageFile', $io);

        $io->section('Options');
        $this->processCollection($options, 'imageFile', $io);

        $io->success('Toutes les images ont été régénérées avec succès.');

        return Command::SUCCESS;
    }

    private function processCollection(array $entities, string $fieldName, SymfonyStyle $io): void
    {
        $progressBar = $io->createProgressBar(count($entities) * count(self::FILTERS));
        $progressBar->start();

        foreach ($entities as $entity) {
            $assetPath = $this->storage->resolveUri($entity, $fieldName);

            if (!$assetPath) {
                $progressBar->advance(count(self::FILTERS));
                continue;
            }

            // Nettoyage du path (on retire le / initial)
            $path = ltrim(parse_url($assetPath, PHP_URL_PATH), '/');

            foreach (self::FILTERS as $filter) {
                try {
                    // 1. On supprime le cache existant pour ce filtre spécifique
                    $this->cacheManager->remove($path, $filter);

                    // 2. On récupère la source originale
                    $binary = $this->dataManager->find($filter, $path);
                    // 3. On applique les filtres et on stocke le nouveau résultat
                    $this->cacheManager->store(
                        $this->filterManager->applyFilter($binary, $filter),
                        $path,
                        $filter
                    );
                } catch (\Exception $e) {
                    dd($e);
                    // Erreur ignorée (souvent fichier source manquant sur le disque)
                }
                $progressBar->advance();
            }
        }

        $progressBar->finish();
        $io->newLine(2);
    }
}
