<?php

declare(strict_types=1);

namespace Maestro\Core\Console\Commands;

use Illuminate\Console\Command;
use Maestro\Core\Services\MaestroLinkService;

class MaestroLinkCommand extends Command
{
    protected $signature = 'maestro:link
        {path : Absolute or relative path to the Maestro-new repository}';

    protected $description = 'Link vendor/maestro/core and @maestro/core to a local Maestro-new checkout';

    public function handle(MaestroLinkService $linker): int
    {
        $path = (string) $this->argument('path');
        if (! str_starts_with($path, DIRECTORY_SEPARATOR)) {
            $path = base_path($path);
        }

        try {
            $linker->link($path, function (string $buffer): void {
                $this->output->write($buffer);
            });
        } catch (\Throwable $e) {
            $this->error($e->getMessage());

            return self::FAILURE;
        }

        $this->newLine();
        $this->info('Maestro CORE linked successfully.');
        $this->line('  • rm -rf node_modules/.vite');
        $this->line('  • Restart composer run dev (or npm run dev)');
        $this->line('  • php artisan maestro:unlink before commit/CI/deploy');

        return self::SUCCESS;
    }
}
