<?php

namespace AutoAdmin\Bundle\Core\Command;

use Exception;
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 Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;

#[AsCommand(
    name: 'aa:install',
    description: 'Installs the required AutoAdmin configuration files.'
)]
class AutoAdminInstallerCommand extends Command
{
    private string $bundleDir;

    public function __construct()
    {
        parent::__construct();
        $this->bundleDir = dirname(__DIR__, 3);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('AutoAdmin Installer');

        $bootstrapDir = $this->bundleDir.'/resources/bootstrap_files';
        $projectDir = $this->getProjectDir();

        if (!is_dir($bootstrapDir)) {
            $io->error('bootstrap_files directory not found in the bundle');

            return Command::FAILURE;
        }

        $io->note('Copying configuration files');

        $fs = new Filesystem();
        $finder = new Finder();
        $finder->files()
            ->ignoreDotFiles(false)
            ->in($bootstrapDir);

        $errors = [];

        foreach ($finder as $file) {
            $relativeFilePath = $file->getRelativePathname();
            $destinationPath = $projectDir.'/'.$relativeFilePath;
            $destinationDir = dirname($destinationPath);

            try {
                if (!is_dir($destinationDir)) {
                    $fs->mkdir($destinationDir);
                }

                $fs->copy($file->getRealPath(), $destinationPath, true);
            } catch (Exception $e) {
                $errors[] = sprintf('Error copying "%s": %s', $relativeFilePath, $e->getMessage());
            }
        }

        if (!empty($errors)) {
            $io->warning('Some files could not be copied:');
            foreach ($errors as $error) {
                $io->text('- '.$error);
            }
        }

        $io->note('Removing useless files and directories');

        $filesToDelete = [
            'assets/app.js',
            'assets/bootstrap.js',
            'assets/controllers.json',
            'assets/controllers/',
            'assets/styles/',
            'assets/vendor/',
        ];

        foreach ($filesToDelete as $path) {
            $fullPath = $projectDir.'/'.$path;
            if (file_exists($fullPath)) {
                try {
                    $fs->remove($fullPath);
                } catch (Exception $e) {
                    $io->warning(sprintf('Could not remove "%s": %s', $path, $e->getMessage()));
                }
            }
        }

        $io->success('Installation complete.');

        return Command::SUCCESS;
    }

    private function getProjectDir(): string
    {
        return dirname($this->bundleDir, 3);
    }
}
