<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Compiler;

use PpPhp\Core\Platform\DI\Compiler\Pipeline\CompilerPipeline;
use PpPhp\Core\Platform\DI\Repository\DefinitionRepository;

final class ContainerCompiler
{
    private CompilerPipeline $pipeline;

    public function __construct(private readonly CompiledDefinitionWriter $writer = new CompiledDefinitionWriter(), ?CompilerPipeline $pipeline = null)
    {
        $this->pipeline = $pipeline ?? CompilerPipeline::default();
    }

    public function pipeline(): CompilerPipeline { return $this->pipeline; }
    public function addStage(CompilerStageInterface $stage): void { $this->pipeline->add($stage); }

    public function compile(DefinitionRepository $definitions, string $basePath, ?string $outputFile = null): CompilerReport
    {
        $context = new CompilerContext($definitions, $basePath);
        $audit = $this->pipeline->run($context);
        $outputFile = $outputFile ?? rtrim($basePath, DIRECTORY_SEPARATOR) . '/storage/cache/di/compiled-definitions.php';
        $this->writer->write($context, $outputFile);
        return new CompilerReport(date('c'), count($context->compiled()), $audit->stageNames(), $context->warnings(), $outputFile, $context->metadata());
    }
}
