<?php

/**
 * Registers installed built blocks from wp-content/lolacore-blocks.
 *
 * @package LolaCore\BlockBuilder\Registry
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\BlockBuilder\Registry;

use LolaCore\BlockBuilder\PostType\BlockPostType;
use LolaCore\BlockBuilder\Registry\BlockRuntimeRegistrar;

if (! defined('ABSPATH')) {
	exit;
}

/**
 * Spectra-style host registration: LolaCore scans lolacore-blocks/* on init.
 */
final class BlockRegistry {

	public function register(): void {
		add_action('init', array($this, 'registerInstalledBlocks'), 20);
	}

	public function registerInstalledBlocks(): void {
		$root = BlockPostType::runtimeBlocksRoot();
		if (! is_dir($root)) {
			return;
		}

		$pattern = $root . '/*/block.json';
		$matches = glob($pattern);
		if (! is_array($matches)) {
			return;
		}

		foreach ($matches as $block_json_path) {
			if (! is_string($block_json_path) || ! file_exists($block_json_path)) {
				continue;
			}

			$directory = dirname($block_json_path);
			$this->registerDirectory($directory);
		}
	}

	/**
	 * Register or re-register a single block directory (after install/overwrite).
	 */
	public function registerDirectory( string $directory ): void {
		BlockRuntimeRegistrar::registerDirectory($directory);
	}

	public function registerInstallSlug( string $install_slug ): void {
		$this->registerDirectory(BlockPostType::runtimePathForSlug($install_slug));
	}

	public function unregisterInstallSlug( string $install_slug ): void {
		$directory = BlockPostType::runtimePathForSlug($install_slug);
		if ($directory === '' || ! file_exists($directory . '/block.json')) {
			return;
		}

		$raw = file_get_contents($directory . '/block.json');
		if (! is_string($raw) || $raw === '') {
			return;
		}

		$decoded = json_decode($raw, true);
		if (! is_array($decoded)) {
			return;
		}

		$block_name = isset($decoded['name']) ? (string) $decoded['name'] : '';
		if ($block_name === '' || ! function_exists('unregister_block_type')) {
			return;
		}

		$registry = \WP_Block_Type_Registry::get_instance();
		if ($registry->is_registered($block_name)) {
			unregister_block_type($block_name);
		}
	}

	public function isBlockRegistered( string $block_name ): bool {
		if ($block_name === '' || ! class_exists(\WP_Block_Type_Registry::class)) {
			return false;
		}

		return \WP_Block_Type_Registry::get_instance()->is_registered($block_name);
	}
}
