<?php

namespace WordpressModels\DependencyInjection\CliCommandAttributes;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\Extension;
use WordpressModels\DependencyInjection\CliCommandAttributes\Attributes\CommandArgument;
use WordpressModels\DependencyInjection\CliCommandAttributes\Attributes\WpCliCommand;

class WpCliCommandAttributesExtension extends Extension
{

    public function load(array $configs, ContainerBuilder $container)
    {
        $container->registerAttributeForAutoconfiguration(WpCliCommand::class, self::tagServices(...));

        $container->register(WpCliCommandRegistry::class)
            ->setPublic(true)
            ->setAutowired(true)
            ->setAutoconfigured(true);
    }

    public static function tagServices(Definition $definition, WpCliCommand $command, \ReflectionMethod|\ReflectionClass $reflection): void
    {
        if ($reflection instanceof \ReflectionClass) {
            // add the base command tag
            $definition->addTag('wp_cli.command_base', [
                'name' => $command->name,
            ]);

            if (!$reflection->hasMethod('__invoke')) {
                return;
            }

            $reflection = $reflection->getMethod('__invoke');
        }


        $synopsis = [];

        // get the argument attributes
        foreach ($reflection->getParameters() as $parameter) {
            $attributes = $parameter->getAttributes(CommandArgument::class);
            foreach ($attributes as $attribute) {
                /** @var CommandArgument $argument */
                $argument = $attribute->newInstance();

                // add the argument to the definition
                $synopsis[] = [
                    'type' => $argument->type,
                    'name' => $argument->name,
                    'description' => $argument->description,
                    'default' => $argument->default,
                    'optional' => $argument->optional,
                    'repeating' => $argument->repeating,
                    'options' => $argument->options,
                ];
            }
        }


        $definition->addTag('wp_cli.command', [
            'method' => $reflection->getName(),
            'name' => $command->name,
            'args' => [
                'longdesc' => $command->description,
                'shortdesc' => $command->shortDescription,
                'when' => $command->when,
                'synopsis' => $synopsis,
            ]
        ]);
    }

}