<?php

/**
 * Block Builder adapter for the shared builder backbone.
 *
 * @package LolaCore\BlockBuilder\Artifact
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\BlockBuilder\Artifact;

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

use LolaCore\BlockBuilder\PostType\BlockPostType;
use LolaCore\Builder\Artifact\ArtifactAdapter;
use LolaCore\Builder\Artifact\FilesMap;

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

/**
 * Maps the lolacore_block library CPT onto the backbone's artifact contract.
 */
final class BlockArtifactAdapter implements ArtifactAdapter {

	public function postType(): string {
		return BlockPostType::POST_TYPE;
	}

	public function metaPrefix(): string {
		return '_lc_bb_';
	}

	public function currentVersion( int $postId ): int {
		return max(1, (int) get_post_meta($postId, BlockPostType::META_VERSION, true));
	}

	/**
	 * Install folder slug under wp-content/lolacore-blocks/.
	 */
	public function slug( int $postId ): string {
		$block_slug = (string) get_post_meta($postId, BlockPostType::META_BLOCK_SLUG, true);
		$stored     = (string) get_post_meta($postId, BlockPostType::META_PLUGIN_SLUG, true);

		return BlockPostType::resolveInstallSlug($block_slug, $stored);
	}

	/**
	 * @return array<int, mixed>
	 */
	public function dependencies( int $postId ): array {
		return array();
	}

	/**
	 * Disk-bound tree: block assets only (no plugin wrapper — FS-D5 revised).
	 */
	public function filesMap( int $postId ): FilesMap {
		if ($this->slug($postId) === '') {
			throw new \Exception(__('Built block install slug is missing.', 'lolacore'));
		}

		return FilesMap::fromArray($this->readBlockFilesMeta($postId));
	}

	/**
	 * PHP validated before install — render.php when present, otherwise empty (static blocks).
	 */
	public function storedPhp( int $postId ): string {
		return $this->runtimePhp($postId);
	}

	public function runtimePhp( int $postId ): string {
		try {
			$files = $this->readBlockFilesMeta($postId);
		} catch (\Exception $e) {
			return '';
		}

		return $files['render.php'] ?? '';
	}

	/**
	 * @return array<string, string>
	 */
	public function readBlockFilesMeta( int $postId ): array {
		$raw = get_post_meta($postId, BlockPostType::META_FILES, true);

		$files = BlockPostType::decodeFilesMeta($raw);
		if ($files === null) {
			throw new \Exception(__('Built block files are missing from the library.', 'lolacore'));
		}

		return $files;
	}

	/**
	 * Persist block files meta from a FilesMap (block assets only, no wrapper).
	 */
	public function persistBlockFiles( int $postId, FilesMap $block_files ): void {
		update_post_meta($postId, BlockPostType::META_FILES, $block_files->all());
	}
}

