<?php

declare(strict_types=1);

namespace App\Framework\Console;

final readonly class SimpleWorkflowExecutor
{
    public function __construct(
        private CommandRegistry $commandRegistry,
        private CommandGroupRegistry $groupRegistry,
        private ConsoleOutputInterface $output
    ) {
    }

    public function executeWorkflow(string $workflowName, array $context = []): bool
    {
        $workflow = $this->groupRegistry->getWorkflow($workflowName);
        if ($workflow === null) {
            $this->output->writeLine("Workflow '{$workflowName}' not found", ConsoleColor::RED);

            return false;
        }

        $this->output->writeLine("🔄 Starting workflow: {$workflow['name']}", ConsoleColor::BRIGHT_CYAN);

        if (! empty($workflow['description'])) {
            $this->output->writeLine($workflow['description'], ConsoleColor::GRAY);
        }

        $this->output->newLine();

        $stepNumber = 1;
        $totalSteps = count($workflow['steps']);

        foreach ($workflow['steps'] as $step) {
            $workflowStep = $step instanceof WorkflowStep ? $step : WorkflowStep::fromArray($step);

            $this->output->writeLine(
                "Step {$stepNumber}/{$totalSteps}: {$workflowStep->getCommand()}",
                ConsoleColor::BRIGHT_WHITE
            );

            $args = ['console', $workflowStep->getCommand()];
            $exitCode = $this->commandRegistry->execute($args);

            if ($exitCode->value === 0) {
                $this->output->writeLine('  ✅ Success', ConsoleColor::GREEN);
            } else {
                $this->output->writeLine('  ❌ Failed', ConsoleColor::RED);
                if ($workflow['stopOnError']) {
                    return false;
                }
            }

            $stepNumber++;
        }

        $this->output->newLine();
        $this->output->writeLine('🎉 Workflow completed successfully!', ConsoleColor::BRIGHT_GREEN);

        return true;
    }
}
