<?php

/**
 * Single Playground host plugin that registers a block from lolacore-blocks.
 *
 * @package LolaCore\BlockBuilder\Playground
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\BlockBuilder\Playground;

// phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Diagnostic exception messages; escaped at REST/chat presentation layer.

use LolaCore\BlockBuilder\Registry\BlockRuntimeRegistrar;

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

/**
 * Deterministic Playground-only loader — not used on the live site (BlockRegistry handles that).
 */
final class BlockPlaygroundHost {

	public const PLUGIN_SLUG = 'lolacore-bb-playground-host';

	public static function mainFileRelPath(): string {
		return self::PLUGIN_SLUG . '.php';
	}

	/**
	 * @param string $install_slug Sanitized folder under wp-content/lolacore-blocks/.
	 */
	public static function buildHostPhp( string $install_slug, string $title ): string {
		$install_slug = sanitize_title($install_slug);
		$title        = self::sanitizeHeaderLine($title !== '' ? $title : 'LolaCore Block Preview');

		$registration_body = BlockRuntimeRegistrar::registrationPhpBody($install_slug);

		return '<?php' . "\n"
			. '/**' . "\n"
			. ' * Plugin Name: ' . $title . ' (Playground preview)' . "\n"
			. ' * Description: Temporary host that registers a LolaCore built block for Playground testing.' . "\n"
			. ' * Version: 1.0.0' . "\n"
			. ' * Requires at least: 6.9' . "\n"
			. ' * Requires PHP: 8.1' . "\n"
			. ' * Author: LolaCore' . "\n"
			. ' * License: GPL-2.0-or-later' . "\n"
			. ' */' . "\n\n"
			. 'if ( ! defined( \'ABSPATH\' ) ) {' . "\n"
			. "\texit;\n"
			. '}' . "\n\n"
			. '$lolacore_bb_register_block = static function (): void {' . "\n"
			. $registration_body
			. '};' . "\n\n"
			. "add_action( 'init', \$lolacore_bb_register_block, 20 );\n\n"
			. '// Blueprint activatePlugin may load this file after init on the same request.' . "\n"
			. "if ( did_action( 'init' ) ) {\n"
			. "\t\$lolacore_bb_register_block();\n"
			. '}' . "\n";
	}

	private static function sanitizeHeaderLine( string $value ): string {
		$value = str_replace(array("\r", "\n"), ' ', $value);
		$value = str_replace('*/', '* /', $value);
		$value = preg_replace('/\s+/', ' ', $value) ?? '';

		return trim($value);
	}
}

