<?php
/** Atomic, bounded writers for verified OceanWP 4.2.2 free Customizer settings. */

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

/** @return array<string,mixed> */
function wpagent_oceanwp_free_surface_writer_columns_schema( int $maximum ): array {
	$column = array( 'type' => 'integer', 'minimum' => 1, 'maximum' => $maximum );
	return array(
		'type'                 => 'object',
		'properties'           => array( 'desktop' => $column, 'tablet' => $column, 'mobile' => $column ),
		'minProperties'        => 1,
		'maxProperties'        => 3,
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_oceanwp_free_surface_writer_settings_schema( string $scope ): array {
	if ( 'footer' === $scope ) {
		return array(
			'type' => 'object', 'properties' => array(
				'widgets_enabled' => array( 'type' => 'boolean' ),
				'widgets_visibility' => array( 'type' => 'string', 'enum' => array( 'all-devices', 'hide-tablet', 'hide-mobile', 'hide-tablet-mobile' ) ),
				'widgets_columns' => wpagent_oceanwp_free_surface_writer_columns_schema( 4 ),
				'bottom_enabled' => array( 'type' => 'boolean' ),
				'bottom_visibility' => array( 'type' => 'string', 'enum' => array( 'all-devices', 'hide-tablet', 'hide-mobile', 'hide-tablet-mobile' ) ),
				'copyright_text' => array( 'type' => 'string', 'maxLength' => WPAGENT_OCEANWP_FREE_SURFACE_MAX_HOOK_BYTES ),
			), 'minProperties' => 1, 'maxProperties' => 6, 'additionalProperties' => false,
		);
	}
	if ( 'blog' === $scope ) {
		$layouts = array( 'right-sidebar', 'left-sidebar', 'full-width', 'full-screen', 'both-sidebars' );
		return array(
			'type' => 'object', 'properties' => array(
				'archive_layout' => array( 'type' => 'string', 'enum' => $layouts ),
				'archive_style' => array( 'type' => 'string', 'enum' => array( 'large-entry', 'grid-entry', 'thumbnail-entry' ) ),
				'grid_columns' => wpagent_oceanwp_free_surface_writer_columns_schema( 6 ),
				'excerpt_length' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 500 ),
				'pagination_style' => array( 'type' => 'string', 'enum' => array( 'standard', 'infinite_scroll', 'load_more', 'next_prev' ) ),
				'single_layout' => array( 'type' => 'string', 'enum' => $layouts ),
				'single_content_width' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 2000 ),
			), 'minProperties' => 1, 'maxProperties' => 7, 'additionalProperties' => false,
		);
	}
	if ( 'breadcrumbs' === $scope ) {
		return array(
			'type' => 'object', 'properties' => array(
				'enabled' => array( 'type' => 'boolean' ),
				'source' => array( 'type' => 'string', 'enum' => array( 'default' ) ),
				'position' => array( 'type' => 'string', 'enum' => array( 'absolute-right', 'under-title' ) ),
			), 'minProperties' => 1, 'maxProperties' => 3, 'additionalProperties' => false,
		);
	}
	$layouts = array( 'right-sidebar', 'left-sidebar', 'full-width', 'full-screen', 'both-sidebars' );
	return array(
		'type' => 'object', 'properties' => array(
			'shop_layout' => array( 'type' => 'string', 'enum' => $layouts ),
			'product_style' => array( 'type' => 'string', 'enum' => array( 'default', 'hover' ) ),
			'grid_list_enabled' => array( 'type' => 'boolean' ),
			'result_count_enabled' => array( 'type' => 'boolean' ),
			'pagination_style' => array( 'type' => 'string', 'enum' => array( 'standard', 'infinite_scroll', 'load_more' ) ),
			'product_layout' => array( 'type' => 'string', 'enum' => $layouts ),
		), 'minProperties' => 1, 'maxProperties' => 6, 'additionalProperties' => false,
	);
}

/** @return array<string,mixed> */
function wpagent_oceanwp_free_surface_writer_output_schema( string $scope ): array {
	$settings = 'footer' === $scope
		? wpagent_oceanwp_free_surface_footer_schema()
		: ( 'blog' === $scope
			? wpagent_oceanwp_free_surface_blog_schema()
			: ( 'breadcrumbs' === $scope ? wpagent_oceanwp_free_surface_breadcrumbs_schema() : wpagent_oceanwp_free_surface_woocommerce_schema() ) );
	$properties = array(
		'version' => array( 'type' => 'string', 'enum' => array( WPAGENT_OCEANWP_FREE_SURFACE_THEME_VERSION ) ),
		'settings' => $settings,
		'previous_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		'state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		'changed' => array( 'type' => 'boolean' ),
		'verified' => array( 'type' => 'boolean' ),
	);
	$required = array( 'version', 'settings', 'previous_hash', 'state_hash', 'changed', 'verified' );
	if ( 'woocommerce' === $scope ) {
		$properties['available'] = array( 'type' => 'boolean', 'enum' => array( true ) );
		$required[]              = 'available';
	}
	return array( 'type' => 'object', 'properties' => $properties, 'required' => $required, 'additionalProperties' => false );
}

/** @return array<string,mixed> */
function wpagent_oceanwp_free_surface_writer_ability( string $scope, string $label, string $description, string $callback ): array {
	return array(
		'label' => $label,
		'description' => $description,
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object', 'properties' => array(
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'settings' => wpagent_oceanwp_free_surface_writer_settings_schema( $scope ),
			), 'required' => array( 'expected_hash', 'settings' ), 'additionalProperties' => false,
		),
		'output_schema' => wpagent_oceanwp_free_surface_writer_output_schema( $scope ),
		'execute_callback' => $callback,
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false ) ),
	);
}

function wpagent_ability_update_oceanwp_footer_customizer(): array {
	return wpagent_oceanwp_free_surface_writer_ability(
		'footer',
		__( 'OceanWP-Footer aktualisieren', 'wp-agent-companion' ),
		__( 'Aktualisiert begrenzte freie OceanWP-Footer-Widgets- und Copyright-Einstellungen mit vollständigem Theme-Mods-Compare-and-Swap, Rücklesen und selektivem Rollback.', 'wp-agent-companion' ),
		'wpagent_exec_update_oceanwp_footer_customizer'
	);
}

function wpagent_ability_update_oceanwp_blog_customizer(): array {
	return wpagent_oceanwp_free_surface_writer_ability(
		'blog',
		__( 'OceanWP-Blog aktualisieren', 'wp-agent-companion' ),
		__( 'Aktualisiert begrenzte freie OceanWP-Blog-Archiv- und Einzelbeitragseinstellungen mit vollständigem Theme-Mods-Compare-and-Swap, Rücklesen und selektivem Rollback.', 'wp-agent-companion' ),
		'wpagent_exec_update_oceanwp_blog_customizer'
	);
}

function wpagent_ability_update_oceanwp_woocommerce_customizer(): array {
	return wpagent_oceanwp_free_surface_writer_ability(
		'woocommerce',
		__( 'OceanWP-WooCommerce aktualisieren', 'wp-agent-companion' ),
		__( 'Aktualisiert begrenzte freie OceanWP-Shop- und Produktansichtseinstellungen mit vollständigem Theme-Mods-Compare-and-Swap, Rücklesen und selektivem Rollback.', 'wp-agent-companion' ),
		'wpagent_exec_update_oceanwp_woocommerce_customizer'
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_oceanwp_free_surface_writer_state( string $scope, array $mods ) {
	if ( 'footer' === $scope || 'blog' === $scope || 'breadcrumbs' === $scope ) {
		$settings = 'footer' === $scope
			? wpagent_oceanwp_free_surface_footer( $mods )
			: ( 'blog' === $scope ? wpagent_oceanwp_free_surface_blog( $mods ) : wpagent_oceanwp_free_surface_breadcrumbs( $mods ) );
		return is_wp_error( $settings ) ? $settings : array( 'settings' => $settings );
	}
	$state = wpagent_oceanwp_free_surface_woocommerce( $mods );
	if ( is_wp_error( $state ) ) {
		return $state;
	}
	if ( empty( $state['available'] ) ) {
		return new WP_Error( 'wpagent_oceanwp_woocommerce_unavailable', __( 'WooCommerce ist nicht aktiv. Die OceanWP-Shop-Einstellungen werden nicht geschrieben.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	return $state;
}

/** @param array<string,mixed> $state */
function wpagent_oceanwp_free_surface_writer_hash( string $scope, int $blog_id, array $state ): string {
	return wpagent_oceanwp_free_surface_hash( $scope, $blog_id, 'woocommerce' === $scope ? $state : $state['settings'] );
}

/** @return string|WP_Error */
function wpagent_oceanwp_free_surface_writer_copyright( $value ) {
	if ( ! is_string( $value )
		|| strlen( $value ) > WPAGENT_OCEANWP_FREE_SURFACE_MAX_HOOK_BYTES
		|| wp_check_invalid_utf8( $value, true ) !== $value
		|| html_entity_decode( $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) !== $value
		|| preg_match( '/[\x00-\x1F\x7F\x{202A}-\x{202E}\x{2066}-\x{2069}]/u', $value )
		|| wp_strip_all_tags( $value ) !== $value ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_invalid_settings', __( 'Der Copyright-Text muss sicherer reiner Text sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$without_date = str_replace( '[oceanwp_date]', '', $value );
	if ( str_contains( $without_date, '[' ) || str_contains( $without_date, ']' ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_invalid_settings', __( 'Im Copyright-Text ist nur der OceanWP-Datumsplatzhalter erlaubt.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	return $value;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_oceanwp_free_surface_writer_settings( string $scope, $value ) {
	$schema = wpagent_oceanwp_free_surface_writer_settings_schema( $scope );
	if ( ! is_array( $value ) || ! $value || is_wp_error( rest_validate_value_from_schema( $value, $schema, 'settings' ) ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_invalid_settings', __( 'Die OceanWP-Customizer-Einstellungen sind ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$settings = rest_sanitize_value_from_schema( $value, $schema, 'settings' );
	if ( is_wp_error( $settings ) || ! is_array( $settings ) || ! $settings ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_invalid_settings', __( 'Die OceanWP-Customizer-Einstellungen sind ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( isset( $settings['copyright_text'] ) ) {
		$text = wpagent_oceanwp_free_surface_writer_copyright( $settings['copyright_text'] );
		if ( is_wp_error( $text ) ) {
			return $text;
		}
		$settings['copyright_text'] = $text;
	}
	return $settings;
}

/** @param array<string,mixed> $current @param array<string,mixed> $requested @return array<string,mixed> */
function wpagent_oceanwp_free_surface_writer_delta( array $current, array $requested ): array {
	$delta = array();
	foreach ( $requested as $key => $value ) {
		if ( is_array( $value ) ) {
			$children = array();
			foreach ( $value as $child => $child_value ) {
				if ( ! isset( $current[ $key ][ $child ] ) || $current[ $key ][ $child ] !== $child_value ) {
					$children[ $child ] = $child_value;
				}
			}
			if ( $children ) {
				$delta[ $key ] = $children;
			}
		} elseif ( ! array_key_exists( $key, $current ) || $current[ $key ] !== $value ) {
			$delta[ $key ] = $value;
		}
	}
	return $delta;
}

/** @return true|WP_Error */
function wpagent_oceanwp_free_surface_writer_set_mod( array &$mods, string $key, $value ) {
	$old = array_key_exists( $key, $mods ) ? $mods[ $key ] : false;
	try {
		$filtered = apply_filters( "pre_set_theme_mod_{$key}", $value, $old );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_precondition', __( 'OceanWP konnte die Customizer-Änderung nicht sicher vorbereiten.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( maybe_serialize( $filtered ) !== maybe_serialize( $value ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_precondition', __( 'Ein Customizer-Filter hat die geprüfte OceanWP-Änderung verändert.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$mods[ $key ] = $value;
	return true;
}

/** @param array<string,mixed> $mods @param array<string,mixed> $delta @return array<string,mixed>|WP_Error */
function wpagent_oceanwp_free_surface_writer_apply( string $scope, array $mods, array $delta ) {
	$map = array(
		'footer' => array(
			'widgets_enabled' => 'ocean_footer_widgets', 'widgets_visibility' => 'ocean_footer_widgets_visibility',
			'bottom_enabled' => 'ocean_footer_bottom', 'bottom_visibility' => 'ocean_bottom_footer_visibility',
			'copyright_text' => 'ocean_footer_copyright_text',
		),
		'blog' => array(
			'archive_layout' => 'ocean_blog_archives_layout', 'archive_style' => 'ocean_blog_style',
			'excerpt_length' => 'ocean_blog_entry_excerpt_length', 'pagination_style' => 'ocean_blog_pagination_style',
			'single_layout' => 'ocean_blog_single_layout', 'single_content_width' => 'ocean_blog_single_content_width',
		),
		'woocommerce' => array(
			'shop_layout' => 'ocean_woo_shop_layout', 'product_style' => 'ocean_woo_products_style',
			'grid_list_enabled' => 'ocean_woo_grid_list', 'result_count_enabled' => 'ocean_woo_shop_result_count',
			'pagination_style' => 'ocean_woo_pagination_style', 'product_layout' => 'ocean_woo_product_layout',
		),
		'breadcrumbs' => array(
			'enabled' => 'ocean_breadcrumbs', 'source' => 'ocean_breadcrumbs_source',
		),
	);
	foreach ( $map[ $scope ] as $field => $key ) {
		if ( array_key_exists( $field, $delta ) ) {
			$set = wpagent_oceanwp_free_surface_writer_set_mod( $mods, $key, $delta[ $field ] );
			if ( is_wp_error( $set ) ) {
				return $set;
			}
		}
	}
	if ( 'breadcrumbs' === $scope && array_key_exists( 'position', $delta ) ) {
		$set = wpagent_oceanwp_free_surface_writer_set_mod( $mods, 'ocean_breadcrumbs_position', 'absolute-right' === $delta['position'] ? '' : 'under-title' );
		if ( is_wp_error( $set ) ) {
			return $set;
		}
	}
	$columns = 'footer' === $scope
		? array( 'widgets_columns' => array( 'desktop' => 'ocean_footer_widgets_columns', 'tablet' => 'ocean_footer_widgets_tablet_columns', 'mobile' => 'ocean_footer_widgets_mobile_columns' ) )
		: ( 'blog' === $scope ? array( 'grid_columns' => array( 'desktop' => 'ocean_blog_grid_columns', 'tablet' => 'ocean_blog_grid_columns_tablet', 'mobile' => 'ocean_blog_grid_columns_mobile' ) ) : array() );
	foreach ( $columns as $field => $keys ) {
		foreach ( $delta[ $field ] ?? array() as $device => $value ) {
			$set = wpagent_oceanwp_free_surface_writer_set_mod( $mods, $keys[ $device ], $value );
			if ( is_wp_error( $set ) ) {
				return $set;
			}
		}
	}
	return $mods;
}

/** @return array{option_name:string,mods:array<string,mixed>,row:array{raw:string,autoload:string},blog_id:int,version:string}|WP_Error */
function wpagent_oceanwp_free_surface_writer_snapshot() {
	global $wpdb;
	$base = wpagent_oceanwp_free_surface_theme_snapshot();
	if ( is_wp_error( $base ) ) {
		return $base;
	}
	$option_name = wpagent_oceanwp_option_name();
	if ( is_wp_error( $option_name ) ) {
		return $option_name;
	}
	$row = wpagent_companion_read_option_row_direct( $option_name );
	if ( '' !== $wpdb->last_error ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_storage', __( 'Die OceanWP-Theme-Mods konnten nicht direkt gelesen werden.', 'wp-agent-companion' ), array( 'status' => 502 ) );
	}
	if ( ! is_array( $row ) || $row['raw'] !== maybe_serialize( $base['mods'] ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_conflict', __( 'Die OceanWP-Theme-Mods wurden gleichzeitig geändert. Lies den Zustand neu.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	return array( 'option_name' => $option_name, 'mods' => $base['mods'], 'row' => $row, 'blog_id' => $base['blog_id'], 'version' => $base['version'] );
}

/** @return true|WP_Error */
function wpagent_oceanwp_free_surface_cas_write( array $previous, array $next ) {
	global $wpdb;
	$option_name = $previous['option_name'];
	try {
		$prepared = sanitize_option( $option_name, $next );
		$prepared = apply_filters( "pre_update_option_{$option_name}", $prepared, $previous['mods'], $option_name );
		$prepared = apply_filters( 'pre_update_option', $prepared, $option_name, $previous['mods'] );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_precondition', __( 'OceanWP konnte die Theme-Mods nicht sicher vorbereiten.', 'wp-agent-companion' ), array( 'status' => 409, 'mutation_started' => false ) );
	}
	if ( ! is_array( $prepared ) || maybe_serialize( $prepared ) !== maybe_serialize( $next ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_precondition', __( 'Ein Optionsfilter hat die geprüften OceanWP-Theme-Mods verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'mutation_started' => false ) );
	}
	try {
		do_action( "update_option_{$option_name}", $previous['mods'], $next, $option_name );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_write_failed', __( 'OceanWP konnte die Theme-Mods vor dem Schreiben nicht bestätigen.', 'wp-agent-companion' ), array( 'status' => 502, 'mutation_started' => false ) );
	}
	$next_raw = maybe_serialize( $next );
	$changed  = $wpdb->query( $wpdb->prepare(
		"UPDATE {$wpdb->options} SET option_value = %s, autoload = %s WHERE option_name = %s AND HEX(option_value) = HEX(%s) AND HEX(autoload) = HEX(%s)",
		$next_raw, $previous['row']['autoload'], $option_name, $previous['row']['raw'], $previous['row']['autoload']
	) );
	wpagent_companion_forget_option_cache( $option_name, in_array( $previous['row']['autoload'], wp_autoload_values_to_autoload(), true ) );
	if ( 1 !== $changed ) {
		return new WP_Error( false === $changed ? 'wpagent_oceanwp_free_surface_write_failed' : 'wpagent_oceanwp_free_surface_conflict', __( 'Die OceanWP-Theme-Mods konnten nicht atomar gespeichert werden.', 'wp-agent-companion' ), array( 'status' => false === $changed ? 502 : 409, 'mutation_started' => false ) );
	}
	try {
		do_action( 'updated_option', $option_name, $previous['mods'], $next );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_write_failed', __( 'OceanWP konnte die Theme-Mods nach dem Schreiben nicht bestätigen.', 'wp-agent-companion' ), array( 'status' => 502, 'mutation_started' => true ) );
	}
	return true;
}

/** Restores only this request's exact full Theme-Mods row. */
function wpagent_oceanwp_free_surface_rollback( array $previous, array $next ): bool {
	global $wpdb;
	$option_name = $previous['option_name'];
	$current     = wpagent_companion_read_option_row_direct( $option_name );
	$next_raw    = maybe_serialize( $next );
	if ( '' !== $wpdb->last_error || ! is_array( $current ) ) {
		return false;
	}
	if ( $current['raw'] === $previous['row']['raw'] && $current['autoload'] === $previous['row']['autoload'] ) {
		return true;
	}
	if ( $current['raw'] !== $next_raw || $current['autoload'] !== $previous['row']['autoload'] ) {
		return false;
	}
	$changed = $wpdb->query( $wpdb->prepare(
		"UPDATE {$wpdb->options} SET option_value = %s, autoload = %s WHERE option_name = %s AND HEX(option_value) = HEX(%s) AND HEX(autoload) = HEX(%s)",
		$previous['row']['raw'], $previous['row']['autoload'], $option_name, $current['raw'], $current['autoload']
	) );
	wpagent_companion_forget_option_cache( $option_name, in_array( $current['autoload'], wp_autoload_values_to_autoload(), true ) );
	$restored = wpagent_companion_read_option_row_direct( $option_name );
	return 1 === $changed && '' === $wpdb->last_error && is_array( $restored )
		&& $restored['raw'] === $previous['row']['raw'] && $restored['autoload'] === $previous['row']['autoload'];
}

/** @return WP_Error */
function wpagent_oceanwp_free_surface_recovery_required( string $scope ) {
	$data = array( 'status' => 500, 'rollback_verified' => false, 'recovery_required' => true );
	$snapshot = wpagent_oceanwp_free_surface_writer_snapshot();
	if ( is_array( $snapshot ) ) {
		$state = wpagent_oceanwp_free_surface_writer_state( $scope, $snapshot['mods'] );
		if ( is_array( $state ) ) {
			$data['current_hash'] = wpagent_oceanwp_free_surface_writer_hash( $scope, $snapshot['blog_id'], $state );
			$data['current'] = $state;
		}
	}
	return new WP_Error( 'wpagent_oceanwp_free_surface_recovery_required', __( 'Die OceanWP-Änderung wurde nicht vollständig verifiziert. Ein fremder oder unklarer Theme-Mods-Zustand wurde nicht überschrieben. Prüfe den aktuellen Zustand manuell.', 'wp-agent-companion' ), $data );
}

/** @return WP_Error */
function wpagent_oceanwp_free_surface_failure( string $scope, array $previous, array $next, string $lock ): WP_Error {
	if ( get_current_blog_id() !== $previous['blog_id'] || ! wpagent_perm_manage_options() || ! wpagent_oceanwp_refresh_lock( $lock ) || ! wpagent_oceanwp_free_surface_rollback( $previous, $next ) || ! wpagent_oceanwp_refresh_lock( $lock ) ) {
		return wpagent_oceanwp_free_surface_recovery_required( $scope );
	}
	$fresh = wpagent_oceanwp_free_surface_writer_snapshot();
	if ( ! is_array( $fresh ) || $fresh['row']['raw'] !== $previous['row']['raw'] || $fresh['row']['autoload'] !== $previous['row']['autoload'] ) {
		return wpagent_oceanwp_free_surface_recovery_required( $scope );
	}
	return new WP_Error( 'wpagent_oceanwp_free_surface_verification_failed', __( 'Die OceanWP-Änderung konnte nicht bestätigt werden. Der exakt zugeordnete vorherige Theme-Mods-Zustand wurde wiederhergestellt und verifiziert.', 'wp-agent-companion' ), array( 'status' => 502, 'rollback_verified' => true, 'recovery_required' => false ) );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_oceanwp_free_surface_update( string $scope, $input ) {
	$ready = wpagent_oceanwp_free_surface_require_theme();
	if ( is_wp_error( $ready ) ) {
		return $ready;
	}
	$input = is_array( $input ) ? $input : array();
	if ( array_diff( array_keys( $input ), array( 'expected_hash', 'settings' ) ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_invalid_settings', __( 'Die OceanWP-Customizer-Anfrage enthält unbekannte Felder.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$expected_hash = $input['expected_hash'] ?? null;
	if ( ! is_string( $expected_hash ) || ! preg_match( '/^[a-f0-9]{64}$/D', $expected_hash ) ) {
		return new WP_Error( 'wpagent_oceanwp_free_surface_invalid_settings', __( 'expected_hash muss ein SHA-256-Hash sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$settings = wpagent_oceanwp_free_surface_writer_settings( $scope, $input['settings'] ?? null );
	if ( is_wp_error( $settings ) ) {
		return $settings;
	}
	if ( ! wpagent_perm_manage_options() ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$lock = wpagent_oceanwp_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		if ( ! wpagent_perm_manage_options() ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$ready = wpagent_oceanwp_free_surface_require_theme();
		if ( is_wp_error( $ready ) ) {
			return $ready;
		}
		$previous = wpagent_oceanwp_free_surface_writer_snapshot();
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		$before_state = wpagent_oceanwp_free_surface_writer_state( $scope, $previous['mods'] );
		if ( is_wp_error( $before_state ) ) {
			return $before_state;
		}
		$previous_hash = wpagent_oceanwp_free_surface_writer_hash( $scope, $previous['blog_id'], $before_state );
		if ( ! hash_equals( $previous_hash, $expected_hash ) ) {
			return new WP_Error( 'wpagent_oceanwp_free_surface_conflict', __( 'Die OceanWP-Customizer-Einstellungen haben sich seit dem Lesen geändert. Lies sie neu.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $previous_hash ) );
		}
		$writable = wpagent_oceanwp_assert_writable_mode( $previous['mods'] );
		if ( is_wp_error( $writable ) ) {
			return $writable;
		}
		$delta = wpagent_oceanwp_free_surface_writer_delta( $before_state['settings'], $settings );
		if ( ! $delta ) {
			if ( get_current_blog_id() !== $previous['blog_id'] || ! wpagent_perm_manage_options() || ! wpagent_oceanwp_refresh_lock( $lock ) ) {
				return new WP_Error( 'wpagent_oceanwp_lock_lost', __( 'Die OceanWP-Änderung hat ihre exklusive Sperre verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
			}
			return array_merge( array( 'version' => $previous['version'] ), $before_state, array( 'previous_hash' => $previous_hash, 'state_hash' => $previous_hash, 'changed' => false, 'verified' => true ) );
		}
		$next = wpagent_oceanwp_free_surface_writer_apply( $scope, $previous['mods'], $delta );
		if ( is_wp_error( $next ) ) {
			return $next;
		}
		$expected_state = wpagent_oceanwp_free_surface_writer_state( $scope, $next );
		if ( is_wp_error( $expected_state ) || maybe_serialize( $expected_state['settings'] ) === maybe_serialize( $before_state['settings'] ) ) {
			return is_wp_error( $expected_state ) ? $expected_state : new WP_Error( 'wpagent_oceanwp_free_surface_precondition', __( 'OceanWP konnte keine überprüfbare Einstellung ableiten.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$ready = wpagent_oceanwp_free_surface_require_theme();
		if ( get_current_blog_id() !== $previous['blog_id'] || ! wpagent_perm_manage_options() || ! wpagent_oceanwp_refresh_lock( $lock ) ) {
			return new WP_Error( 'wpagent_oceanwp_lock_lost', __( 'Die OceanWP-Änderung hat ihre exklusive Sperre verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		if ( is_wp_error( $ready ) ) {
			return $ready;
		}
		$written = wpagent_oceanwp_free_surface_cas_write( $previous, $next );
		if ( is_wp_error( $written ) ) {
			$data = $written->get_error_data();
			return is_array( $data ) && ! empty( $data['mutation_started'] ) ? wpagent_oceanwp_free_surface_failure( $scope, $previous, $next, $lock ) : $written;
		}
		if ( get_current_blog_id() !== $previous['blog_id'] || ! wpagent_perm_manage_options() || ! wpagent_oceanwp_refresh_lock( $lock ) ) {
			return wpagent_oceanwp_free_surface_failure( $scope, $previous, $next, $lock );
		}
		$fresh = wpagent_oceanwp_free_surface_writer_snapshot();
		if ( is_wp_error( $fresh ) ) {
			return wpagent_oceanwp_free_surface_failure( $scope, $previous, $next, $lock );
		}
		$current = wpagent_oceanwp_free_surface_writer_state( $scope, $fresh['mods'] );
		if ( $fresh['row']['raw'] !== maybe_serialize( $next )
			|| $fresh['row']['autoload'] !== $previous['row']['autoload']
			|| is_wp_error( $current )
			|| maybe_serialize( $current ) !== maybe_serialize( $expected_state )
			|| ! wpagent_oceanwp_refresh_lock( $lock ) ) {
			return wpagent_oceanwp_free_surface_failure( $scope, $previous, $next, $lock );
		}
		if ( 'breadcrumbs' === $scope ) {
			$runtime = wpagent_oceanwp_free_surface_breadcrumbs_runtime_state();
			if ( is_wp_error( $runtime ) || $runtime !== $current['settings']['enabled'] || ! wpagent_oceanwp_refresh_lock( $lock ) ) {
				return wpagent_oceanwp_free_surface_failure( $scope, $previous, $next, $lock );
			}
		}
		return array_merge( array( 'version' => $fresh['version'] ), $current, array(
			'previous_hash' => $previous_hash,
			'state_hash' => wpagent_oceanwp_free_surface_writer_hash( $scope, $fresh['blog_id'], $current ),
			'changed' => true,
			'verified' => true,
		) );
	} finally {
		wpagent_oceanwp_release_lock( $lock );
	}
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_oceanwp_footer_customizer( $input ) {
	return wpagent_oceanwp_free_surface_update( 'footer', $input );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_oceanwp_blog_customizer( $input ) {
	return wpagent_oceanwp_free_surface_update( 'blog', $input );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_oceanwp_woocommerce_customizer( $input ) {
	return wpagent_oceanwp_free_surface_update( 'woocommerce', $input );
}
