<?php
/** Canonical provider-owned wrapper transformations for GenerateBlocks. */

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

/** @return array<int,string> */
function wpagent_builder_block_generateblocks_query_tags(): array {
	return array( 'div', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main' );
}

/** @return array<int,string> */
function wpagent_builder_block_generateblocks_page_number_tags(): array {
	return array( 'div', 'section', 'nav' );
}

/** @return array<int,string> */
function wpagent_builder_block_generateblocks_text_tags(): array {
	return array( 'p', 'span', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' );
}

/** @return array<int,string> */
function wpagent_builder_block_generateblocks_element_tags(): array {
	return array( 'div', 'section', 'article', 'aside', 'main' );
}

/**
 * The agent supplies only an enum. This helper rewrites the exact provider
 * wrapper generated by GenerateBlocks, never caller-provided markup.
 *
 * @param array<string,mixed> $block
 * @param array<string,mixed> $before
 * @param array<string,mixed> $after
 * @return true|WP_Error
 */
function wpagent_builder_block_sync_generateblocks_markup( array &$block, array $before, array $after ) {
	$old_tag = is_string( $before['tagName'] ?? null ) ? $before['tagName'] : '';
	$new_tag = is_string( $after['tagName'] ?? null ) ? $after['tagName'] : '';
	if ( $old_tag === $new_tag ) {
		return true;
	}
	$name = is_string( $block['blockName'] ?? null ) ? $block['blockName'] : '';
	if ( 'generateblocks/query' === $name ) {
		$allowed = wpagent_builder_block_generateblocks_query_tags();
		$class   = 'gb-query';
		$nested  = true;
	} elseif ( 'generateblocks/query-page-numbers' === $name ) {
		$allowed = wpagent_builder_block_generateblocks_page_number_tags();
		$class   = 'gb-query-page-numbers';
		$nested  = false;
	} elseif ( 'generateblocks/text' === $name ) {
		$allowed = wpagent_builder_block_generateblocks_text_tags();
		$class   = 'gb-text';
		$nested  = false;
	} elseif ( 'generateblocks/element' === $name ) {
		$unique_id = is_string( $before['uniqueId'] ?? null ) ? $before['uniqueId'] : '';
		if ( 1 !== preg_match( '/^[A-Za-z0-9_-]{6,64}$/D', $unique_id ) ) {
			return new WP_Error( 'wpagent_builder_block_markup_drift', __( 'Das vorhandene GenerateBlocks-Wrapper-Markup weicht vom kanonischen Providervertrag ab.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$allowed = wpagent_builder_block_generateblocks_element_tags();
		$class   = 'gb-element gb-element-' . $unique_id;
		$nested  = true;
	} else {
		return new WP_Error( 'wpagent_builder_block_markup_target', __( 'Für diesen GenerateBlocks-Block existiert kein freigegebener struktureller Wrappervertrag.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( ! in_array( $old_tag, $allowed, true ) || ! in_array( $new_tag, $allowed, true ) ) {
		return new WP_Error( 'wpagent_builder_block_markup_tag', __( 'Der GenerateBlocks-Wrapper-Tag gehört nicht zum eng freigegebenen Provider-Enum.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( 'generateblocks/text' === $name ) {
		$inner_html    = is_string( $block['innerHTML'] ?? null ) ? $block['innerHTML'] : '';
		$inner_content = $block['innerContent'] ?? null;
		$pattern       = '/\\A<' . preg_quote( $old_tag, '/' ) . ' class="gb-text">([^<>]{1,500})<\\/' . preg_quote( $old_tag, '/' ) . '>\\z/uD';
		if ( ! isset( $block['innerBlocks'] ) || array() !== $block['innerBlocks'] || ! is_array( $inner_content ) || array( $inner_html ) !== $inner_content
			|| 1 !== preg_match( $pattern, $inner_html, $matches )
			|| preg_match( '/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/u', html_entity_decode( $matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) ) {
			return new WP_Error( 'wpagent_builder_block_markup_drift', __( 'Das vorhandene GenerateBlocks-Text-Markup weicht vom eng geprüften Providervertrag ab.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$block['innerHTML']    = '<' . $new_tag . ' class="gb-text">' . $matches[1] . '</' . $new_tag . '>';
		$block['innerContent'] = array( $block['innerHTML'] );
		return true;
	}
	$old_open  = '<' . $old_tag . ' class="' . $class . '">';
	$old_close = '</' . $old_tag . '>';
	$old_html  = $old_open . $old_close;
	$expected_content = $nested ? array( $old_open, null, $old_close ) : array( $old_html );
	if ( $old_html !== ( $block['innerHTML'] ?? null ) || $expected_content !== ( $block['innerContent'] ?? null ) ) {
		return new WP_Error( 'wpagent_builder_block_markup_drift', __( 'Das vorhandene GenerateBlocks-Wrapper-Markup weicht vom kanonischen Providervertrag ab.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$new_open  = '<' . $new_tag . ' class="' . $class . '">';
	$new_close = '</' . $new_tag . '>';
	$block['innerHTML']    = $new_open . $new_close;
	$block['innerContent'] = $nested ? array( $new_open, null, $new_close ) : array( $new_open . $new_close );
	return true;
}
