<?php
/** Verified native Elementor create, update and revision restore abilities. */

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

/** @return array<string,mixed> */
function wpagent_elementor_elements_input_schema(): array {
	return wpagent_elementor_json_document_schema();
}

function wpagent_ability_create_elementor_page(): array {
	return array(
		'label' => __( 'Elementor-Seite erstellen', 'wp-agent-companion' ),
		'description' => __( 'Erstellt eine Elementor-Seite über die öffentliche Dokument-API und prüft Struktur, Einstellungen sowie Frontend-Ausgabe nach dem Speichern.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'title' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 200 ),
				'post_type' => array( 'type' => 'string', 'maxLength' => 64, 'default' => 'page' ),
				'status' => array( 'type' => 'string', 'enum' => array( 'draft', 'pending', 'private', 'publish' ), 'default' => 'draft' ),
				'elements' => wpagent_elementor_elements_input_schema(),
				'settings' => wpagent_elementor_json_document_schema(),
			),
			'required' => array( 'title', 'elements' ),
			'additionalProperties' => false,
		),
		'output_schema' => wpagent_elementor_write_output_schema(),
		'execute_callback' => 'wpagent_exec_create_elementor_page',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false ) ),
	);
}

function wpagent_ability_update_elementor_document(): array {
	return array(
		'label' => __( 'Elementor-Dokument aktualisieren', 'wp-agent-companion' ),
		'description' => __( 'Ersetzt Struktur und/oder Seiteneinstellungen konfliktgeschützt über Elementors Dokument-API. Vorher entsteht eine Sicherheitsrevision; bei unklarer Providerantwort bleibt der aktuelle Zustand zur manuellen Prüfung erhalten.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'post_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'elements' => wpagent_elementor_elements_input_schema(),
				'settings' => wpagent_elementor_json_document_schema(),
			),
			'required' => array( 'post_id', 'expected_hash' ),
			'additionalProperties' => false,
		),
		'output_schema' => wpagent_elementor_write_output_schema(),
		'execute_callback' => 'wpagent_exec_update_elementor_document',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false ) ),
	);
}

function wpagent_ability_restore_elementor_revision(): array {
	return array(
		'label' => __( 'Elementor-Revision wiederherstellen', 'wp-agent-companion' ),
		'description' => __( 'Stellt eine zu diesem Beitrag gehörende Elementor-Revision nur bei unverändertem Konflikt-Hash wieder her und prüft das Ergebnis. Vor dem Restore entsteht eine neue Sicherheitsrevision.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'post_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'revision_id' => array( 'type' => 'integer', 'minimum' => 1 ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required' => array( 'post_id', 'revision_id', 'expected_hash' ),
			'additionalProperties' => false,
		),
		'output_schema' => wpagent_elementor_write_output_schema(),
		'execute_callback' => 'wpagent_exec_restore_elementor_revision',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => true, 'idempotent' => false ) ),
	);
}

/** @return array<string,mixed> */
function wpagent_elementor_write_output_schema(): array {
	$schema = wpagent_elementor_document_output_schema();
	$schema['properties']['verified'] = array( 'type' => 'boolean' );
	$schema['properties']['frontend_verified'] = array( 'type' => 'boolean' );
	$schema['properties']['previous_hash'] = array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' );
	$schema['properties']['revision_id'] = array( 'type' => 'integer', 'minimum' => 0 );
	$schema['properties']['safety_revision_id'] = array( 'type' => 'integer', 'minimum' => 0 );
	$schema['properties']['recovery_required'] = array( 'type' => 'boolean' );
	return $schema;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_create_elementor_page( $input ) {
	$input = is_array( $input ) ? $input : array();
	if ( ! wpagent_elementor_available() ) {
		return wpagent_elementor_unavailable_error();
	}
	$title = is_string( $input['title'] ?? null ) ? trim( $input['title'] ) : '';
	$title_length = function_exists( 'mb_strlen' ) ? mb_strlen( $title, 'UTF-8' ) : strlen( $title );
	if ( '' === $title || $title_length > 200 ) {
		return new WP_Error( 'wpagent_elementor_title', __( 'Der Titel muss 1-200 Zeichen lang sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$post_type = sanitize_key( (string) ( $input['post_type'] ?? 'page' ) );
	$post_type_object = get_post_type_object( $post_type );
	if ( ! $post_type_object || ! post_type_supports( $post_type, 'elementor' ) ) {
		return new WP_Error( 'wpagent_elementor_post_type', __( 'Der Beitragstyp unterstützt Elementor nicht.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( ! current_user_can( $post_type_object->cap->create_posts ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$status = (string) ( $input['status'] ?? 'draft' );
	if ( ! in_array( $status, array( 'draft', 'pending', 'private', 'publish' ), true ) ) {
		return new WP_Error( 'wpagent_bad_status', __( 'Ungültiger Beitragsstatus.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$status_cap = wpagent_check_post_status_cap( $post_type, $status );
	if ( is_wp_error( $status_cap ) ) {
		return $status_cap;
	}
	$elements = wpagent_elementor_json_document_input( $input['elements'] ?? null, 'wpagent_elementor_validate_document_elements' );
	$has_settings = array_key_exists( 'settings', $input );
	$settings = $has_settings ? wpagent_elementor_json_document_input( $input['settings'], 'wpagent_elementor_validate_document_settings' ) : array();
	if ( is_wp_error( $elements ) || is_wp_error( $settings ) ) {
		return is_wp_error( $elements ) ? $elements : $settings;
	}

	$owner_id = get_current_user_id();
	$post_id = wp_insert_post( wp_slash( array( 'post_title' => $title, 'post_status' => 'draft', 'post_type' => $post_type ) ), true );
	if ( is_wp_error( $post_id ) ) {
		return $post_id;
	}
	$candidate = wpagent_core_mutator_created_post_candidate( $post_id, $post_type, $owner_id );
	if ( ! is_array( $candidate ) ) {
		return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_candidate_unreadable' );
	}
	$lock = wpagent_elementor_acquire_lock( $post_id );
	if ( is_wp_error( $lock ) ) {
		if ( wpagent_core_mutator_delete_created_post_if_current( $candidate, $post_type, $owner_id ) ) {
			return $lock;
		}
		return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_lock_unavailable_cleanup_drift' );
	}
	try {
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_lock_lost_before_provider_write' );
		}
		$loaded = wpagent_elementor_editable_document( $post_id, false );
		if ( is_wp_error( $loaded ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_capability_lost_before_provider_write' );
		}
		$document = $loaded['document'];
		$normalized = wpagent_elementor_normalize_elements( $document, $elements );
		if ( is_wp_error( $normalized ) ) {
			if ( wpagent_core_mutator_delete_created_post_if_current( $candidate, $post_type, $owner_id ) ) {
				return $normalized;
			}
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_normalization_cleanup_drift' );
		}
		$save_data = array( 'elements' => $elements );
		if ( $has_settings ) {
			$save_data['settings'] = $settings;
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_lock_lost_before_save' );
		}
		$prewrite = wpagent_elementor_editable_document( $post_id, false );
		if ( is_wp_error( $prewrite ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_capability_lost_before_save' );
		}
		$document = $prewrite['document'];
		$document->set_is_built_with_elementor( true );
		if ( ! wpagent_elementor_save_document( $document, $save_data, $has_settings ) ) {
			throw new RuntimeException( 'Elementor document save failed.' );
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_lock_lost_after_save' );
		}
		if ( 'draft' !== $status ) {
			if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) || ! current_user_can( 'edit_post', $post_id ) ) {
				return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_capability_or_lock_lost_before_status' );
			}
			$status_result = wp_update_post( array( 'ID' => $post_id, 'post_status' => $status ), true );
			if ( is_wp_error( $status_result ) ) {
				throw new RuntimeException( $status_result->get_error_message() );
			}
			if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
				return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_lock_lost_after_status' );
			}
		}
		$fresh_loaded = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $fresh_loaded ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_capability_lost_before_readback' );
		}
		$state = wpagent_elementor_document_state( $post_id, $fresh_loaded['document'] );
		$verified = $state['built_with_elementor']
			&& wpagent_elementor_elements_contain_requested( $state['elements'], $normalized )
			&& ( ! $has_settings || wpagent_elementor_array_contains( $state['settings'], $settings ) )
			&& $status === get_post_status( $post_id );
		if ( ! $verified ) {
			if ( wpagent_core_mutator_delete_created_post_if_current( $candidate, $post_type, $owner_id ) ) {
				return new WP_Error( 'wpagent_elementor_verify_failed', __( 'Die Elementor-Seite bestand die Rückleseprüfung nicht. Der unveränderte Create-Kandidat wurde entfernt.', 'wp-agent-companion' ), array( 'status' => 500, 'rollback_verified' => true ) );
			}
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_readback_mismatch' );
		}
		$candidate = wpagent_core_mutator_created_post_candidate( $post_id, $post_type, $owner_id );
		if ( ! is_array( $candidate ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_verified_candidate_unreadable' );
		}
		$frontend = wpagent_elementor_verify_frontend( $post_id, $state['element_count'] );
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_lock_lost_after_readback' );
		}
		if ( is_wp_error( $frontend ) ) {
			if ( wpagent_core_mutator_delete_created_post_if_current( $candidate, $post_type, $owner_id ) ) {
				return $frontend;
			}
			return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_frontend_cleanup_drift' );
		}
		$state['verified'] = true;
		$state['frontend_verified'] = true;
		return wpagent_elementor_publicize_result( $state );
	} catch ( Throwable ) {
		if ( wpagent_core_mutator_delete_created_post_if_current( $candidate, $post_type, $owner_id ) ) {
			return new WP_Error( 'wpagent_elementor_create_failed', __( 'Die Elementor-Seite konnte nicht erstellt werden. Der unveränderte Create-Kandidat wurde entfernt.', 'wp-agent-companion' ), array( 'status' => 500, 'rollback_verified' => true ) );
		}
		return wpagent_core_mutator_created_post_recovery_required( $post_id, $post_type, $owner_id, 'elementor_create_exception_cleanup_drift' );
	} finally {
		wpagent_elementor_release_lock( $post_id, $lock );
	}
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_elementor_document( $input ) {
	$input = is_array( $input ) ? $input : array();
	$post_id = absint( $input['post_id'] ?? 0 );
	$loaded = wpagent_elementor_editable_document( $post_id );
	if ( is_wp_error( $loaded ) ) {
		return $loaded;
	}
	$expected_hash = is_string( $input['expected_hash'] ?? null ) ? $input['expected_hash'] : '';
	if ( ! preg_match( '/^[a-f0-9]{64}$/', $expected_hash ) ) {
		return new WP_Error( 'wpagent_elementor_hash', __( 'expected_hash muss ein SHA-256-Hash sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$lock = wpagent_elementor_acquire_lock( $post_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $expected_hash, 'lock_lost_before_initial_read' );
		}
		$loaded = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $loaded ) ) {
			return $loaded;
		}
		$before = wpagent_elementor_document_state( $post_id, $loaded['document'] );
		if ( ! hash_equals( $before['hash'], $expected_hash ) ) {
			return new WP_Error( 'wpagent_elementor_conflict', __( 'Das Elementor-Dokument wurde seit dem Lesen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $before['hash'] ) );
		}
		$has_elements = array_key_exists( 'elements', $input );
		$has_settings = array_key_exists( 'settings', $input );
		if ( ! $has_elements && ! $has_settings ) {
			return new WP_Error( 'wpagent_elementor_no_fields', __( 'elements oder settings ist erforderlich.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$save_data = array();
		$normalized = null;
		$settings = array();
		if ( $has_elements ) {
			$elements = wpagent_elementor_json_document_input( $input['elements'], 'wpagent_elementor_validate_document_elements' );
			if ( is_wp_error( $elements ) ) {
				return $elements;
			}
			$normalized = wpagent_elementor_normalize_elements( $loaded['document'], $elements );
			if ( is_wp_error( $normalized ) ) {
				return $normalized;
			}
			$save_data['elements'] = $elements;
		}
		if ( $has_settings ) {
			$settings = wpagent_elementor_json_document_input( $input['settings'], 'wpagent_elementor_validate_document_settings' );
			if ( is_wp_error( $settings ) ) {
				return $settings;
			}
			$save_data['settings'] = $settings;
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'lock_lost_before_revision' );
		}
		$revision_id = wpagent_elementor_save_revision( $post_id, $before['hash'] );
		if ( is_wp_error( $revision_id ) ) {
			return $revision_id;
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'lock_lost_after_revision' );
		}
		$prewrite = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $prewrite ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'capability_lost_before_provider_write' );
		}
		$prewrite_state = wpagent_elementor_document_state( $post_id, $prewrite['document'] );
		if ( ! hash_equals( $before['hash'], $prewrite_state['hash'] ) ) {
			return new WP_Error( 'wpagent_elementor_conflict', __( 'Das Elementor-Dokument wurde vor dem Speichern verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $prewrite_state['hash'] ) );
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'lock_lost_before_provider_write' );
		}
		try {
			$saved = wpagent_elementor_save_document( $prewrite['document'], $save_data, $has_settings );
		} catch ( Throwable ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'provider_write_exception' );
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'lock_lost_after_provider_write' );
		}
		$fresh_loaded = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $fresh_loaded ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'capability_lost_before_readback' );
		}
		$after = wpagent_elementor_document_state( $post_id, $fresh_loaded['document'] );
		$verified = is_array( $after )
			&& true === $saved
			&& ( ! $has_elements || wpagent_elementor_elements_contain_requested( $after['elements'], $normalized ) )
			&& ( ! $has_settings || wpagent_elementor_array_contains( $after['settings'], $settings ) );
		$frontend = $verified ? wpagent_elementor_verify_frontend( $post_id, $after['element_count'] ) : false;
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'lock_lost_after_readback' );
		}
		if ( ! $verified || is_wp_error( $frontend ) ) {
			return wpagent_elementor_recovery_required( $post_id, $before['hash'], 'provider_readback_or_frontend_verification_failed' );
		}
		$after['verified'] = true;
		$after['frontend_verified'] = true;
		$after['previous_hash'] = $before['hash'];
		$after['revision_id'] = $revision_id;
		return wpagent_elementor_publicize_result( $after );
	} finally {
		wpagent_elementor_release_lock( $post_id, $lock );
	}
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_restore_elementor_revision( $input ) {
	$input = is_array( $input ) ? $input : array();
	$post_id = absint( $input['post_id'] ?? 0 );
	$revision_id = absint( $input['revision_id'] ?? 0 );
	$loaded = wpagent_elementor_editable_document( $post_id );
	if ( is_wp_error( $loaded ) ) {
		return $loaded;
	}
	$expected_hash = is_string( $input['expected_hash'] ?? null ) ? $input['expected_hash'] : '';
	if ( ! preg_match( '/^[a-f0-9]{64}$/', $expected_hash ) ) {
		return new WP_Error( 'wpagent_elementor_hash', __( 'expected_hash muss ein SHA-256-Hash sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$lock = wpagent_elementor_acquire_lock( $post_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $expected_hash, 'lock_lost_before_restore_read' );
		}
		$loaded = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $loaded ) ) {
			return $loaded;
		}
		$current = wpagent_elementor_document_state( $post_id, $loaded['document'] );
		if ( ! hash_equals( $current['hash'], $expected_hash ) ) {
			return new WP_Error( 'wpagent_elementor_conflict', __( 'Das Elementor-Dokument wurde seit dem Lesen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $current['hash'] ) );
		}
		if ( $post_id !== (int) wp_is_post_revision( $revision_id ) ) {
			return new WP_Error( 'wpagent_elementor_bad_revision', __( 'Die Revision gehört nicht zu diesem Beitrag.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$revision_document = \Elementor\Plugin::$instance->documents->get( $revision_id, false );
		if ( ! is_object( $revision_document ) || ! $revision_document->is_built_with_elementor() ) {
			return new WP_Error( 'wpagent_elementor_bad_revision', __( 'Die Revision enthält kein wiederherstellbares Elementor-Dokument.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$target = wpagent_elementor_document_state( $revision_id, $revision_document );
		$target_elements_valid = wpagent_elementor_validate_elements( $target['elements'] );
		if ( is_wp_error( $target_elements_valid ) ) {
			return $target_elements_valid;
		}
		$target_settings_valid = wpagent_elementor_validate_settings( $target['settings'] );
		if ( is_wp_error( $target_settings_valid ) ) {
			return $target_settings_valid;
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'lock_lost_before_safety_revision' );
		}
		$pre_revision = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $pre_revision ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'capability_lost_before_safety_revision' );
		}
		$pre_revision_state = wpagent_elementor_document_state( $post_id, $pre_revision['document'] );
		if ( ! hash_equals( $current['hash'], $pre_revision_state['hash'] ) ) {
			return new WP_Error( 'wpagent_elementor_conflict', __( 'Das Elementor-Dokument wurde vor der Sicherheitsrevision verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $pre_revision_state['hash'] ) );
		}
		$safety_revision_id = wpagent_elementor_save_revision( $post_id, $current['hash'] );
		if ( is_wp_error( $safety_revision_id ) ) {
			return $safety_revision_id;
		}
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'lock_lost_after_safety_revision' );
		}
		$prewrite = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $prewrite ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'capability_lost_before_restore' );
		}
		$prewrite_state = wpagent_elementor_document_state( $post_id, $prewrite['document'] );
		if ( ! hash_equals( $current['hash'], $prewrite_state['hash'] ) ) {
			return new WP_Error( 'wpagent_elementor_conflict', __( 'Das Elementor-Dokument wurde vor dem Wiederherstellen verändert.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $prewrite_state['hash'] ) );
		}
		$restored = wpagent_elementor_restore_revision_internal( $post_id, $revision_id, $target['hash'], $current['hash'], $lock );
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'lock_lost_after_restore_write' );
		}
		$fresh_loaded = wpagent_elementor_editable_document( $post_id );
		if ( is_wp_error( $fresh_loaded ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'capability_lost_before_restore_readback' );
		}
		$after = wpagent_elementor_document_state( $post_id, $fresh_loaded['document'] );
		$verified = $restored && is_array( $after ) && hash_equals( $target['hash'], $after['hash'] );
		$frontend = $verified ? wpagent_elementor_verify_frontend( $post_id, $after['element_count'] ) : false;
		if ( ! wpagent_elementor_lock_checkpoint( $post_id, $lock ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'lock_lost_after_restore_readback' );
		}
		if ( ! $verified || is_wp_error( $frontend ) ) {
			return wpagent_elementor_recovery_required( $post_id, $current['hash'], 'restore_readback_or_frontend_verification_failed' );
		}
		$after['verified'] = true;
		$after['frontend_verified'] = true;
		$after['previous_hash'] = $current['hash'];
		$after['revision_id'] = $revision_id;
		$after['safety_revision_id'] = $safety_revision_id;
		return wpagent_elementor_publicize_result( $after );
	} finally {
		wpagent_elementor_release_lock( $post_id, $lock );
	}
}
