<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Console\Commands;

use PpPhp\Core\Platform\Console\AbstractCommand;
use PpPhp\Core\Platform\Console\ConsolePath;
use PpPhp\Core\Platform\DI\Compiler\Factory\FactoryCachePaths;
use PpPhp\Core\Platform\DI\Integration\PlatformContainerRuntime;
use PpPhp\Core\Platform\DI\Performance\PerformanceTimer;

final class ContainerCompileCommand extends AbstractCommand
{
    public function name(): string { return 'container:compile'; }
    public function description(): string { return 'Compile integrated DI container definitions and factories.'; }

    public function handle(array $arguments = []): int
    {
        $base = ConsolePath::basePath();
        $runtime = new PlatformContainerRuntime($base);

        $timer = new PerformanceTimer();
        $timer->start();
        $result = $runtime->compile();
        $timer->stop();

        $data = $result['report'];
        $factory = $data['metadata']['factoryGeneration'] ?? ['generated' => 0, 'attempted' => 0, 'failed' => 0];
        $pipeline = $data['metadata']['pipelineAudit'] ?? ['stageNames' => $data['stages'] ?? []];

        $this->title('PPphp DI Container Compile');
        $this->line('Definitions: ' . $data['definitions']);
        $this->line('Runtime registered: ' . $result['registered']);
        $this->line('Stages: ' . implode(', ', $pipeline['stageNames']));
        $this->line('Factories generated: ' . $factory['generated'] . ' / ' . $factory['attempted']);
        $this->line('Factory failures: ' . $factory['failed']);
        $this->line('Factory files on disk: ' . $result['factoryFiles']);
        $this->line('Time: ' . $timer->milliseconds() . ' ms');
        $this->line('Definitions output: ' . str_replace($base . '/', '', $data['outputFile']));
        $this->line('Factories output: ' . FactoryCachePaths::relativeDirectory());

        return $factory['failed'] > 0 ? 1 : 0;
    }
}
