<?php

declare(strict_types=1);

final class MyronAdminComponentGuard
{
    private array $usage = [];
    private array $allowed;

    public function __construct()
    {
        $path = myronAppRoot() . '/data/runtime-definitions/components/admin-vocabulary-v0.1.0.json';
        $decoded = is_file($path) ? json_decode((string) file_get_contents($path), true) : [];
        $this->allowed = array_fill_keys(array_merge((array) ($decoded['atoms'] ?? []), (array) ($decoded['primitives'] ?? [])), true);
    }

    public function registerSection(string $componentKey, array $attrs = []): string
    {
        if (!isset($this->allowed[$componentKey])) {
            throw new InvalidArgumentException('Unknown admin component: ' . $componentKey);
        }
        $this->usage[$componentKey] = ($this->usage[$componentKey] ?? 0) + 1;
        $class = trim((string) ($attrs['class'] ?? $attrs['className'] ?? ''));
        $tag = trim((string) ($attrs['tag'] ?? 'section')) ?: 'section';
        return '<' . $tag . ' class="' . myronEscape($class !== '' ? $class : 'sg-section') . '" data-myron-component="' . myronEscape($componentKey) . '">';
    }

    public function requireWrapper(string $componentKey): void
    {
        if (!isset($this->allowed[$componentKey])) {
            throw new InvalidArgumentException('Unknown admin component: ' . $componentKey);
        }
    }

    public function summary(): array
    {
        return ['usage' => $this->usage, 'allowed' => array_keys($this->allowed)];
    }
}

function myronAdminComponentGuard(): MyronAdminComponentGuard
{
    static $guard = null;
    if ($guard instanceof MyronAdminComponentGuard) {
        return $guard;
    }
    $guard = new MyronAdminComponentGuard();
    return $guard;
}
