<?php

declare(strict_types=1);

namespace Fennec\Console;

/**
 * Aide optionnelle pour séparer arguments positionnels et options (--nom ou --nom=valeur)
 * à partir du tableau brut reçu par CommandInterface::execute().
 */
final class Input
{
    /** @var array<string, string|bool> */
    private readonly array $options;

    /** @var list<string> */
    private readonly array $arguments;

    /**
     * @param list<string> $rawArguments
     */
    public function __construct(array $rawArguments)
    {
        $options = [];
        $positional = [];

        foreach ($rawArguments as $rawArgument) {
            if (!\str_starts_with($rawArgument, '--')) {
                $positional[] = $rawArgument;

                continue;
            }

            $withoutPrefix = \substr($rawArgument, 2);

            if (\str_contains($withoutPrefix, '=')) {
                [$key, $value] = \explode('=', $withoutPrefix, 2);
                $options[$key] = $value;
            } else {
                $options[$withoutPrefix] = true;
            }
        }

        $this->options = $options;
        $this->arguments = $positional;
    }

    public function getOption(string $name, string|bool|null $default = null): string|bool|null
    {
        return $this->options[$name] ?? $default;
    }

    public function getArgument(int $index, ?string $default = null): ?string
    {
        return $this->arguments[$index] ?? $default;
    }

    /**
     * @return list<string>
     */
    public function getArguments(): array
    {
        return $this->arguments;
    }
}
