<?php
/** Transactional executor for the version-bound static Spectra color contract. */

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

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_spectra_static_heading_colors( $input ) {
	$input = is_array( $input ) ? $input : array();
	$post_id = absint( $input['post_id'] ?? 0 );
	$path = is_array( $input['path'] ?? null ) ? $input['path'] : array();
	$path_ok = wpagent_native_block_validate_path( $path );
	if ( is_wp_error( $path_ok ) ) {
		return $path_ok;
	}
	$heading_color = $input['heading_color'] ?? null;
	$description_color = $input['description_color'] ?? null;
	$separator_requested = array_key_exists( 'separator_color', $input );
	$separator_color = $separator_requested ? $input['separator_color'] : null;
	if ( false === wpagent_spectra_static_advanced_heading_color_input( $heading_color )
		|| false === wpagent_spectra_static_advanced_heading_color_input( $description_color )
		|| ( $separator_requested && false === wpagent_spectra_static_advanced_heading_color_input( $separator_color ) ) ) {
		return new WP_Error( 'wpagent_spectra_static_heading_color', __( 'Farben müssen exakt inherit oder sechsstellige Hex-Farben sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$heading_color = 'inherit' === $heading_color ? 'inherit' : strtolower( $heading_color );
	$description_color = 'inherit' === $description_color ? 'inherit' : strtolower( $description_color );
	$separator_color = ! $separator_requested || 'inherit' === $separator_color ? $separator_color : strtolower( $separator_color );
	$expected_hash = is_string( $input['expected_hash'] ?? null ) ? $input['expected_hash'] : '';
	if ( ! preg_match( '/^[a-f0-9]{64}$/D', $expected_hash ) ) {
		return new WP_Error( 'wpagent_spectra_static_heading_hash', __( 'expected_hash muss ein SHA-256-Hash sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$lock = wpagent_site_editor_acquire_lock( 'spectra-static-heading', (string) $post_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$contract = wpagent_spectra_static_advanced_heading_contract();
		if ( is_wp_error( $contract ) ) {
			return $contract;
		}
		$before = wpagent_native_block_document_state( $post_id );
		if ( is_wp_error( $before ) ) {
			return $before;
		}
		if ( ! hash_equals( $before['hash'], $expected_hash ) ) {
			return new WP_Error( 'wpagent_spectra_static_heading_conflict', __( 'Das Blockdokument wurde seit dem Lesen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $before['hash'] ) );
		}
		if ( strlen( $before['content'] ) > WPAGENT_SPECTRA_MAX_CONTENT_BYTES ) {
			return new WP_Error( 'wpagent_spectra_static_heading_content_limit', __( 'Das Blockdokument ist größer als 1 MB und wird nicht automatisch geändert.', 'wp-agent-companion' ), array( 'status' => 413 ) );
		}
		$blocks = parse_blocks( $before['content'] );
		if ( serialize_blocks( $blocks ) !== $before['content'] ) {
			return new WP_Error( 'wpagent_spectra_static_heading_noncanonical_document', __( 'Das bestehende statische Blockdokument ist nicht exakt parse- und serialisierbar und wird deshalb nicht automatisch verändert.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$target = wpagent_spectra_static_advanced_heading_patch_colors( $blocks, $path, $heading_color, $description_color, $separator_requested ? $separator_color : null );
		if ( is_wp_error( $target ) ) {
			return $target;
		}
		$before_markup = wpagent_spectra_static_advanced_heading_static_markup_at_path( $blocks, $path, $target['block_id'] );
		if ( is_wp_error( $before_markup ) ) {
			return $before_markup;
		}
		$result = static function( array $state, bool $changed, int $revision_id, array $cache ) use ( $post_id, $path, $heading_color, $description_color, $separator_requested, $separator_color, $contract, $target, $before, $before_markup ): array {
			$output = array(
				'post_id' => $post_id, 'block_name' => $target['block_name'], 'path' => $path,
				'heading_color' => $heading_color, 'description_color' => $description_color,
				'provider_version' => $contract['provider_version'], 'changed' => $changed, 'verified' => true,
				'revision_id' => $revision_id, 'rendered_html_length' => strlen( $before_markup ),
				'previous_hash' => $before['hash'], 'hash' => $state['hash'], 'cache' => $cache,
			);
			if ( $separator_requested ) {
				$output['separator_color'] = $separator_color;
			}
			return $output;
		};
		if ( ! $target['changed'] ) {
			if ( ! wpagent_site_editor_refresh_lock( 'spectra-static-heading', (string) $post_id, $lock ) ) {
				return new WP_Error( 'wpagent_spectra_static_heading_lock_lost', __( 'Die exklusive Sperre ging vor der No-op-Prüfung verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
			}
			$fresh = wpagent_spectra_static_heading_verify_noop_state(
				$post_id,
				$before['content'],
				$path,
				$target['block_id'],
				$before_markup,
				static function( array &$candidate ) use ( $path, $heading_color, $description_color, $separator_requested, $separator_color ) {
					return wpagent_spectra_static_advanced_heading_patch_colors( $candidate, $path, $heading_color, $description_color, $separator_requested ? $separator_color : null );
				}
			);
			if ( is_wp_error( $fresh ) ) {
				return $fresh;
			}
			if ( ! wpagent_site_editor_lock_is_owned( 'spectra-static-heading', (string) $post_id, $lock ) ) {
				return new WP_Error( 'wpagent_spectra_static_heading_lock_lost', __( 'Die exklusive Sperre ging während der No-op-Prüfung verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
			}
			return $result( $fresh, false, 0, wpagent_spectra_static_heading_noop_cache() );
		}
		$candidate = serialize_blocks( $blocks );
		if ( strlen( $candidate ) > WPAGENT_SPECTRA_MAX_CONTENT_BYTES || serialize_blocks( parse_blocks( $candidate ) ) !== $candidate ) {
			return new WP_Error( 'wpagent_spectra_static_heading_serialization', __( 'Das geänderte statische Blockdokument ist nicht stabil serialisierbar oder überschreitet 1 MB.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$before_report = array( 'block_count' => 0, 'freeform_count' => 0, 'block_types' => array() );
		$after_report = array( 'block_count' => 0, 'freeform_count' => 0, 'block_types' => array() );
		wpagent_native_block_report_walk( parse_blocks( $before['content'] ), $before_report );
		wpagent_native_block_report_walk( parse_blocks( $candidate ), $after_report );
		$candidate_blocks = parse_blocks( $candidate );
		$candidate_target = wpagent_spectra_static_advanced_heading_patch_colors( $candidate_blocks, $path, $heading_color, $description_color, $separator_requested ? $separator_color : null );
		$candidate_markup = wpagent_spectra_static_advanced_heading_static_markup_at_path( $candidate_blocks, $path, $target['block_id'] );
		if ( $before_report !== $after_report || ! is_array( $candidate_target ) || $candidate_target['changed']
			|| ! is_string( $candidate_markup ) || ! hash_equals( $before_markup, $candidate_markup ) ) {
			return new WP_Error( 'wpagent_spectra_static_heading_structure_changed', __( 'Der Farb-Patch würde das Blockdokument oder das statische Ziel-Markup verändern und wurde abgelehnt.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		if ( ! wpagent_site_editor_refresh_lock( 'spectra-static-heading', (string) $post_id, $lock ) ) {
			return new WP_Error( 'wpagent_spectra_static_heading_lock_lost', __( 'Die exklusive Sperre ging vor der statischen Spectra-Änderung verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$revision_id = wpagent_native_block_create_revision( $post_id, $before['content'] );
		if ( is_wp_error( $revision_id ) ) {
			return $revision_id;
		}
		if ( ! wpagent_site_editor_refresh_lock( 'spectra-static-heading', (string) $post_id, $lock ) ) {
			return new WP_Error( 'wpagent_spectra_static_heading_lock_lost', __( 'Die exklusive Sperre ging vor dem statischen Spectra-Write verloren.', 'wp-agent-companion' ), array( 'status' => 409, 'revision_id' => $revision_id ) );
		}
		$saved = wpagent_native_block_write_if_current( $post_id, $before['content'], $candidate );
		if ( is_wp_error( $saved ) ) {
			$data = $saved->get_error_data();
			return new WP_Error( $saved->get_error_code(), $saved->get_error_message(), array_merge( is_array( $data ) ? $data : array(), array( 'revision_id' => $revision_id ) ) );
		}
		if ( ! wpagent_site_editor_lock_is_owned( 'spectra-static-heading', (string) $post_id, $lock ) ) {
			return wpagent_spectra_static_heading_lock_lost_after_write( $revision_id );
		}
		$verify = static function() use ( $post_id, $candidate, $path, $heading_color, $description_color, $separator_requested, $separator_color, $target, $before_markup ) {
			$raw = wpagent_native_block_raw_content( $post_id );
			$state = wpagent_native_block_document_state( $post_id );
			$verified_blocks = is_string( $raw ) && $raw === $candidate && is_array( $state ) && $state['content'] === $candidate ? parse_blocks( $raw ) : array();
			$verified_target = $verified_blocks ? wpagent_spectra_static_advanced_heading_patch_colors( $verified_blocks, $path, $heading_color, $description_color, $separator_requested ? $separator_color : null ) : null;
			$verified_markup = $verified_blocks ? wpagent_spectra_static_advanced_heading_static_markup_at_path( $verified_blocks, $path, $target['block_id'] ) : null;
			return is_array( $verified_target ) && ! $verified_target['changed'] && is_string( $verified_markup ) && hash_equals( $before_markup, $verified_markup ) ? $state : false;
		};
		$after = $verify();
		if ( false === $after ) {
			return wpagent_spectra_static_heading_write_error( 'wpagent_spectra_static_heading_verify_failed', __( 'Die statische Spectra-Überschrift bestand die Rückleseprüfung nicht.', 'wp-agent-companion' ), $revision_id, wpagent_native_block_rollback( $post_id, $before['content'], $candidate ) );
		}
		if ( ! wpagent_site_editor_refresh_lock( 'spectra-static-heading', (string) $post_id, $lock ) ) {
			return wpagent_spectra_static_heading_lock_lost_after_write( $revision_id );
		}
		$cache = wpagent_spectra_static_heading_refresh_cache( $post_id );
		if ( ! wpagent_site_editor_lock_is_owned( 'spectra-static-heading', (string) $post_id, $lock ) ) {
			return wpagent_spectra_static_heading_lock_lost_after_write( $revision_id );
		}
		if ( ! $cache['verified'] || false === ( $after_cache = $verify() ) ) {
			return wpagent_spectra_static_heading_write_error( 'wpagent_spectra_static_heading_cache_failed', __( 'Spectras Cache oder Farb-Read-back konnte nicht verifiziert aktualisiert werden.', 'wp-agent-companion' ), $revision_id, wpagent_spectra_static_heading_rollback_after_cache( $post_id, $before['content'], $candidate ) );
		}
		if ( ! wpagent_site_editor_refresh_lock( 'spectra-static-heading', (string) $post_id, $lock ) ) {
			return wpagent_spectra_static_heading_lock_lost_after_write( $revision_id );
		}
		return $result( $after_cache, true, $revision_id, $cache );
	} finally {
		wpagent_site_editor_release_lock( 'spectra-static-heading', (string) $post_id, $lock );
	}
}
