<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\HostSystemUpdatePostApplyException;
use Illuminate\Support\Facades\Artisan;
use Throwable;

/**
 * 在当前 PHP 进程内通过 Artisan::call 执行白名单命令（不依赖 proc_open）。
 */
final class InProcessHostSystemUpdateArtisanCommandHandler implements HostSystemUpdateArtisanCommandHandler
{
    /**
     * @param  list<string>  $arguments
     */
    public function execute(string $command, array $arguments, ?int $timeoutSeconds): HostSystemUpdateArtisanCommandResult
    {
        $startedAt = now()->utc();
        $startedMicro = microtime(true);

        try {
            $exitCode = Artisan::call($command, $this->normalizeArtisanArguments($arguments));
            $output = Artisan::output();
        } catch (Throwable) {
            throw HostSystemUpdatePostApplyException::commandFailed($command, 1);
        }

        $finishedAt = now()->utc();
        $durationMs = max(0, (int) round((microtime(true) - $startedMicro) * 1000));

        return new HostSystemUpdateArtisanCommandResult(
            command: $command,
            arguments: array_values($arguments),
            exitCode: $exitCode,
            stdout: HostSystemUpdateArtisanOutputSanitizer::sanitize($output),
            stderr: '',
            startedAt: $startedAt,
            finishedAt: $finishedAt,
            durationMs: $durationMs,
        );
    }

    /**
     * @param  list<string>  $arguments
     * @return array<string, bool|string>
     */
    private function normalizeArtisanArguments(array $arguments): array
    {
        $normalized = [];

        foreach ($arguments as $argument) {
            if (! is_string($argument) || ! str_starts_with($argument, '--')) {
                continue;
            }

            $body = substr($argument, 2);

            if ($body === '') {
                continue;
            }

            if (str_contains($body, '=')) {
                [$name, $value] = explode('=', $body, 2);
                $normalized[$name] = $value;

                continue;
            }

            $normalized[$body] = true;
        }

        return $normalized;
    }
}
