#!/usr/bin/env php
<?php

declare(strict_types=1);

$autoloadFile = null;
$args = [$argv[0]];
for ($i = 1; $i < $argc; $i++) {
    if ($argv[$i] === '--autoload-file') {
        if (!isset($argv[$i + 1])) {
            fwrite(STDERR, 'The --autoload-file option requires a file path' . PHP_EOL);
            exit(1);
        }

        $autoloadFile = $argv[++$i];
    } elseif (str_starts_with($argv[$i], '--autoload-file=')) {
        $autoloadFile = substr($argv[$i], strlen('--autoload-file='));
    } else {
        $args[] = $argv[$i];
    }
}

if ($autoloadFile === '') {
    fwrite(STDERR, 'The --autoload-file option requires a file path' . PHP_EOL);
    exit(1);
}

// Load the custom file first, in addition to the default autoloader below
if ($autoloadFile !== null) {
    if (!is_file($autoloadFile)) {
        fwrite(STDERR, "Error: autoload file not found: $autoloadFile\n");
        exit(1);
    }

    require_once $autoloadFile;
}

// Find default autoloader
$defaultAutoload = current(array_filter([
    __DIR__ . '/../vendor/autoload.php',
    __DIR__ . '/../../../autoload.php',
    __DIR__ . '/../../../../autoload.php',
], fn (string $p): bool => file_exists($p))) ?: null;

if ($defaultAutoload === null) {
    fwrite(STDERR, "Error: Could not find Composer autoloader.\n");
    fwrite(STDERR, "Please run 'composer install' first.\n");
    exit(1);
}

require_once $defaultAutoload;

use NeuronAI\Console\NeuronCli;

try {
    $command = new NeuronCli();
    $exitCode = $command->run($args);
    exit($exitCode);
} catch (Throwable $e) {
    fwrite(STDERR, "Fatal Error: " . $e->getMessage() . "\n");
    exit(1);
}
