<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Build;

use PpPhp\Core\Designer\Build\Contracts\BuildManifest;
use PpPhp\Core\Designer\Generation\Contracts\GeneratedApplication;
use PpPhp\Core\Designer\Generation\DesignerGenerationRuntime;

final class DesignerBuildRuntime
{
    private array $operations = [];

    public function build(GeneratedApplication $application): BuildManifest
    {
        $manifest = (new DesignerBuildPipeline())->build($application);
        $this->record('build', ['applicationId' => $application->applicationId(), 'artifacts' => count($manifest->artifacts())]);

        return $manifest;
    }

    public function buildCrudApplication(string $appId, string $title, array $tables): BuildManifest
    {
        $application = (new DesignerGenerationRuntime())->generateCrudApplication($appId, $title, $tables);
        return $this->build($application);
    }

    public function stats(BuildManifest $manifest): array
    {
        $summary = $manifest->summary();

        return [
            'operations' => count($this->operations),
            'artifacts' => $summary['artifacts'] ?? 0,
            'generatedPages' => $summary['pages'] ?? 0,
            'routes' => $summary['routes'] ?? 0,
            'assets' => $summary['assets'] ?? 0,
            'bytes' => $summary['bytes'] ?? 0,
        ];
    }

    public function operations(): array { return $this->operations; }

    private function record(string $operation, array $payload): void
    {
        $this->operations[] = ['operation' => $operation, 'payload' => $payload, 'createdAt' => date('c')];
    }
}
