<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\DI\Integration;

use PpPhp\Core\Platform\DI\Compiler\ContainerCompiler;
use PpPhp\Core\Platform\DI\Compiler\Factory\FactoryCachePaths;
use PpPhp\Core\Platform\DI\Container;

final class PlatformContainerRuntime
{
    private ?Container $container = null;
    private PlatformContainerFactory $factory;

    public function __construct(private readonly string $basePath)
    {
        $this->factory = new PlatformContainerFactory();
    }

    public function container(): Container
    {
        if (!$this->container instanceof Container) {
            $this->container = $this->factory->create($this->basePath);
        }

        return $this->container;
    }

    public function compile(): array
    {
        $container = $this->container();
        $report = (new ContainerCompiler())->compile($container->definitionRepository(), $this->basePath);
        $data = $report->toArray();

        $factoryFiles = is_dir(FactoryCachePaths::directory($this->basePath))
            ? glob(FactoryCachePaths::directory($this->basePath) . '/*.php')
            : [];

        return [
            'report' => $data,
            'registered' => count($this->factory->registered()),
            'warnings' => $this->factory->warnings(),
            'factoryFiles' => count($factoryFiles ?: []),
        ];
    }

    public function summary(): array
    {
        $container = $this->container();

        return [
            'definitions' => count($container->definitions()),
            'aliases' => count($container->aliasRepository()->all()),
            'tags' => count($container->tagRepository()->all()),
            'registered' => count($this->factory->registered()),
            'warnings' => count($this->factory->warnings()),
        ];
    }
}
