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

use Symfony\Component\Console\Input\ArgvInput;

define('LARAVEL_START', microtime(true));

// Register the Composer autoloader...
require __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';

$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);

// Fix for Laravel 12: Ensure commands resolved via ContainerCommandLoader get the Laravel instance
// We need to bootstrap first to register commands, then replace the loader
$app->loadDeferredProviders();
$kernel->bootstrap();

// Now replace the loader after commands are registered
$kernelReflection = new \ReflectionClass($kernel);
if ($kernelReflection->hasMethod('getArtisan')) {
    $getArtisanMethod = $kernelReflection->getMethod('getArtisan');
    $getArtisanMethod->setAccessible(true);
    $artisan = $getArtisanMethod->invoke($kernel);
    
    if ($artisan instanceof \Illuminate\Console\Application) {
        $artisanReflection = new \ReflectionClass($artisan);
        $parentReflection = $artisanReflection->getParentClass();
        
        if ($parentReflection && $parentReflection->hasProperty('commandLoader')) {
            $commandLoaderProperty = $parentReflection->getProperty('commandLoader');
            $commandLoaderProperty->setAccessible(true);
            $currentLoader = $commandLoaderProperty->getValue($artisan);
            
            if ($currentLoader instanceof \Illuminate\Console\ContainerCommandLoader) {
                // Get the command map now that commands are registered
                $commandMapProperty = $artisanReflection->getProperty('commandMap');
                $commandMapProperty->setAccessible(true);
                $commandMap = $commandMapProperty->getValue($artisan);
                
                // Replace with our custom loader that wraps the original loader
                // This allows lazy command registration while ensuring Laravel instance is set
                $artisan->setCommandLoader(new \App\Console\ContainerCommandLoader(
                    $app,
                    $commandMap ?: [],
                    $currentLoader // Pass original loader for lazy loading
                ));
            }
        }
    }
}

$status = $kernel->handle(
    $input = new ArgvInput(),
    new Symfony\Component\Console\Output\ConsoleOutput()
);

$kernel->terminate($input, $status);

exit($status);
