<?php
declare(strict_types=1);

namespace Celena\Core\Template;

/**
 * Список доступных тем (читает theme.json из templates/<slug>/).
 */
final class ThemeManager
{
    public function __construct(private readonly string $templatesPath)
    {
    }

    /** @return array<int, array{slug:string, name:string, version:string, author:?string, path:string}> */
    public function all(): array
    {
        $themes = [];
        foreach (glob($this->templatesPath . '/*', GLOB_ONLYDIR) ?: [] as $dir) {
            $slug = basename($dir);
            // admin не считается темой фронта
            if ($slug === 'admin') {
                continue;
            }
            $manifest = $dir . '/theme.json';
            $meta = ['name' => $slug, 'version' => '0.0.0', 'author' => null];
            if (is_file($manifest)) {
                $data = json_decode((string) file_get_contents($manifest), true);
                if (is_array($data)) {
                    $meta = array_merge($meta, $data);
                }
            }
            $themes[] = [
                'slug' => $slug,
                'name' => (string) $meta['name'],
                'version' => (string) $meta['version'],
                'author' => $meta['author'] ?? null,
                'path' => $dir,
            ];
        }
        return $themes;
    }

    public function exists(string $slug): bool
    {
        return is_dir($this->templatesPath . '/' . $slug);
    }
}
