<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiTheme\Theme;

final class ThemeRegistry
{
    /** @var array<string, ThemeDefinition> */
    private array $definitions = [];

    /**
     * @param array<string, array{path?: string|null, templates_path?: string|null, translations_path?: string|null, assets_path?: string|null, public_path?: string|null, package?: string|null}> $themes
     */
    public function __construct(
        private readonly string $activeThemeName,
        array $themes,
    ) {
        foreach ($themes as $name => $theme) {
            if (!isset($theme['path']) || !\is_string($theme['path'])) {
                continue;
            }

            $this->definitions[$name] = $this->createDefinitionFromConfig($name, $theme);
        }
    }

    public function active(): ThemeDefinition
    {
        if (!isset($this->definitions[$this->activeThemeName])) {
            throw new \RuntimeException(\sprintf('The active Viti theme "%s" is not registered.', $this->activeThemeName));
        }

        return $this->definitions[$this->activeThemeName];
    }

    /**
     * @return array<string, ThemeDefinition>
     */
    public function all(): array
    {
        return $this->definitions;
    }

    /**
     * @param array{path?: string|null, templates_path?: string|null, translations_path?: string|null, assets_path?: string|null, public_path?: string|null, package?: string|null} $theme
     */
    private function createDefinitionFromConfig(string $name, array $theme): ThemeDefinition
    {
        $path = $theme['path'];
        $metadataPath = mb_rtrim($path, '/').'/theme.json';
        $metadata = [];

        if (is_file($metadataPath)) {
            $decoded = json_decode((string) file_get_contents($metadataPath), true, flags: \JSON_THROW_ON_ERROR);
            if (\is_array($decoded)) {
                $metadata = $decoded;
            }
        }

        return new ThemeDefinition(
            $name,
            \is_string($metadata['label'] ?? null) ? $metadata['label'] : $name,
            \is_string($metadata['version'] ?? null) ? $metadata['version'] : '0.0.0',
            $path,
            $metadata,
            \is_string($theme['templates_path'] ?? null) ? $theme['templates_path'] : 'templates',
            \is_string($theme['assets_path'] ?? null) ? $theme['assets_path'] : 'assets',
            \is_string($theme['translations_path'] ?? null) ? $theme['translations_path'] : 'translations',
            \is_string($theme['public_path'] ?? null) ? $theme['public_path'] : null,
            \is_string($theme['package'] ?? null) ? $theme['package'] : null,
        );
    }
}
