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

declare(strict_types=1);

/**
 * camelia/orm command line.
 *
 * Ships the commands that need no knowledge of the consumer's code (seed, doctor). Scaffolding
 * commands write into the current working directory, so run this from the project root.
 */

use Camelia\Orm\Console\Application;
use Camelia\Orm\Console\Command\DoctorCommand;
use Camelia\Orm\Console\Command\MakeModelCommand;
use Camelia\Orm\Console\Command\MakeSeederCommand;
use Camelia\Orm\Console\Command\SeedCommand;
use Camelia\Orm\Console\Output;
use Camelia\Orm\Orm;
use Camelia\Orm\Seeding\SeederRunner;

$autoload = __DIR__ . '/../vendor/autoload.php';

if (!is_file($autoload)) {
    fwrite(STDERR, "Run composer install first.\n");
    exit(1);
}

require $autoload;

// The consumer's own autoloader is loaded when the binary is invoked from their project, so their
// seeders and models resolve. Composer already registers it by way of vendor/bin.
$ormFactory = static fn(): Orm => Orm::fromEnv();

$application = (new Application('camelia-orm', '1.0.0'))->add(
    new SeedCommand($ormFactory, static fn(Orm $orm): SeederRunner => new SeederRunner($orm)),
    new DoctorCommand($ormFactory),
    new MakeModelCommand(),
    new MakeSeederCommand(),
);

$decorated = stream_isatty(STDOUT) && getenv('NO_COLOR') === false;

exit($application->run($_SERVER['argv'] ?? [], Output::toStream(STDOUT, $decorated)));
