<?php

declare(strict_types=1);

namespace App\Util;

final readonly class ParsedCommand
{
    /**
     * @param list<string> $args
     */
    public function __construct(
        public string $name,
        public array $args,
        public string $raw,
        public string $tail,
    ) {}

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

    public function argInt(int $index, int $default = 0): int
    {
        $value = $this->args[$index] ?? '';
        return $value === '' ? $default : (int) $value;
    }

    public static function parse(string $text): ?self
    {
        $text = trim($text);
        if ($text === '' || !str_starts_with($text, '/')) {
            return null;
        }
        $parts = preg_split('/\s+/', $text) ?: [];
        $head = array_shift($parts) ?? '';
        if ($head === '') {
            return null;
        }
        if (str_contains($head, ':')) {
            [$name, $param] = explode(':', $head, 2) + [1 => ''];
            if ($param !== '') {
                array_unshift($parts, $param);
            }
        } else {
            $name = $head;
        }
        $name = ltrim($name, '/');
        $tail = implode(' ', $parts);
        return new self(
            name: $name,
            args: array_values($parts),
            raw: $text,
            tail: $tail,
        );
    }
}
