<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Compiler;

final class EventCompilerService
{
    public function __construct(
        private readonly EventCompilerPipeline $pipeline,
        private readonly EventArtifactWriter $writer = new EventArtifactWriter()
    ) {}

    public static function default(): self
    {
        return new self(EventCompilerPipeline::default());
    }

    public function compile(string $basePath): EventCompilerReport
    {
        $basePath = $this->normalizeBasePath($basePath);
        $report = $this->pipeline->compile($basePath);
        $this->writer->writeJson(EventCompilerPaths::reportFile($basePath), $report->toArray());
        return $report;
    }

    public function normalizeBasePath(string $basePath): string
    {
        $basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
        $real = realpath($basePath);
        return $real !== false ? $real : $basePath;
    }
}
