<?php
/** Verified create, duplicate, move and delete operations for Elementor subtrees. */

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

/** @return array<string,mixed> */
function wpagent_elementor_tree_target_input_properties(): array {
	return array(
		'post_id'       => array( 'type' => 'integer' ),
		'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		'parent_id'     => array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_-]{1,64}$' ),
		'index'         => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => WPAGENT_ELEMENTOR_MAX_ELEMENTS ),
	);
}

/** @return array<string,mixed> */
function wpagent_elementor_tree_write_output_schema(): array {
	$schema = wpagent_elementor_write_output_schema();
	$schema['properties']['operation'] = array( 'type' => 'string' );
	$schema['properties']['changed'] = array( 'type' => 'boolean' );
	$schema['properties']['element_id'] = array( 'type' => 'string' );
	$schema['properties']['path'] = array( 'type' => 'array', 'items' => array( 'type' => 'integer' ) );
	$schema['properties']['previous_path'] = array( 'type' => 'array', 'items' => array( 'type' => 'integer' ) );
	$schema['properties']['element'] = array( 'type' => 'object', 'additionalProperties' => true );
	$schema['properties']['deleted_element'] = array( 'type' => 'object', 'additionalProperties' => true );
	return $schema;
}

function wpagent_ability_create_elementor_element(): array {
	$properties = wpagent_elementor_tree_target_input_properties();
	$properties['element'] = array( 'type' => 'object', 'additionalProperties' => true );
	return array(
		'label' => __( 'Elementor-Element erstellen', 'wp-agent-companion' ),
		'description' => __( 'Erstellt einen sicheren Elementor-Teilbaum an einer bestimmten Position. Alle Element-IDs werden neu erzeugt; Konfliktschutz, Revision, Rückleseprüfung, Frontend-Prüfung und Rollback sind verpflichtend.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'post_id', 'expected_hash', 'element' ) ),
		'output_schema' => wpagent_elementor_tree_write_output_schema(),
		'execute_callback' => 'wpagent_exec_create_elementor_element',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false ) ),
	);
}

function wpagent_ability_duplicate_elementor_element(): array {
	$properties = wpagent_elementor_tree_target_input_properties();
	$properties['element_id'] = array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_-]{1,64}$' );
	return array(
		'label' => __( 'Elementor-Element duplizieren', 'wp-agent-companion' ),
		'description' => __( 'Dupliziert einen vorhandenen Elementor-Teilbaum mit neuen IDs und fügt ihn an einer bestimmten Position ein. Die Quelle bleibt unverändert.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'post_id', 'element_id', 'expected_hash' ) ),
		'output_schema' => wpagent_elementor_tree_write_output_schema(),
		'execute_callback' => 'wpagent_exec_duplicate_elementor_element',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false ) ),
	);
}

function wpagent_ability_move_elementor_element(): array {
	$properties = wpagent_elementor_tree_target_input_properties();
	$properties['element_id'] = array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_-]{1,64}$' );
	return array(
		'label' => __( 'Elementor-Element verschieben', 'wp-agent-companion' ),
		'description' => __( 'Verschiebt einen Elementor-Teilbaum ohne seine ID oder Einstellungen zu verändern. Selbst- und Nachfahrenziele werden abgelehnt.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'post_id', 'element_id', 'expected_hash' ) ),
		'output_schema' => wpagent_elementor_tree_write_output_schema(),
		'execute_callback' => 'wpagent_exec_move_elementor_element',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_delete_elementor_element(): array {
	return array(
		'label' => __( 'Elementor-Element löschen', 'wp-agent-companion' ),
		'description' => __( 'Löscht einen Elementor-Teilbaum erst nach ausdrücklicher Bestätigung. Vorher entsteht eine wiederherstellbare Revision.', 'wp-agent-companion' ),
		'category' => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'post_id' => array( 'type' => 'integer' ),
				'element_id' => array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_-]{1,64}$' ),
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'confirm' => array( 'type' => 'boolean' ),
			),
			'required' => array( 'post_id', 'element_id', 'expected_hash', 'confirm' ),
		),
		'output_schema' => wpagent_elementor_tree_write_output_schema(),
		'execute_callback' => 'wpagent_exec_delete_elementor_element',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => true, 'idempotent' => false ) ),
	);
}

/** @return array{post_id:int,expected_hash:string}|WP_Error */
function wpagent_elementor_parse_tree_write_request( array $input ) {
	$post_id = absint( $input['post_id'] ?? 0 );
	$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 ) );
	}
	$loaded = wpagent_elementor_editable_document( $post_id );
	if ( is_wp_error( $loaded ) ) {
		return $loaded;
	}
	return array( 'post_id' => $post_id, 'expected_hash' => $expected_hash );
}

/**
 * @param callable(array<int,array<string,mixed>>,array<string,mixed>):array<string,mixed>|WP_Error $mutation Receives the mutable element tree and the immutable pre-write state.
 * @return array<string,mixed>|WP_Error
 */
function wpagent_elementor_commit_tree_mutation( int $post_id, string $expected_hash, string $operation, callable $mutation ) {
	$lock = wpagent_elementor_acquire_lock( $post_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$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'] ) );
		}
		$current_valid = wpagent_elementor_validate_elements( $before['elements'] );
		if ( is_wp_error( $current_valid ) ) {
			return $current_valid;
		}
		try {
			$mutation_result = $mutation( $before['elements'], $before );
		} catch ( Throwable ) {
			return new WP_Error( 'wpagent_elementor_mutation_failed', __( 'Die Elementor-Strukturänderung konnte nicht vorbereitet werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
		}
		if ( is_wp_error( $mutation_result ) ) {
			return $mutation_result;
		}
		$elements = $mutation_result['elements'] ?? null;
		if ( ! is_array( $elements ) || ! array_is_list( $elements ) ) {
			return new WP_Error( 'wpagent_elementor_mutation_failed', __( 'Die Elementor-Strukturänderung lieferte keine gültige Elementliste.', 'wp-agent-companion' ), array( 'status' => 500 ) );
		}
		$normalized = wpagent_elementor_normalize_elements( $loaded['document'], $elements );
		if ( is_wp_error( $normalized ) ) {
			return $normalized;
		}
		if ( $normalized === $before['elements'] ) {
			$frontend = wpagent_elementor_verify_frontend( $post_id, $before['element_count'] );
			if ( is_wp_error( $frontend ) ) {
				return $frontend;
			}
			$result = $before;
			$result['verified'] = true;
			$result['frontend_verified'] = true;
			$result['previous_hash'] = $before['hash'];
			$result['revision_id'] = 0;
			$result['operation'] = $operation;
			$result['changed'] = false;
			return array_merge( $result, $mutation_result['meta'] ?? array() );
		}
		$revision_id = wpagent_elementor_save_revision( $post_id, $before['hash'] );
		if ( is_wp_error( $revision_id ) ) {
			return $revision_id;
		}
		try {
			$saved = wpagent_elementor_save_document( $loaded['document'], array( 'elements' => $elements ), false );
		} catch ( Throwable ) {
			$rolled_back = wpagent_elementor_restore_revision_internal( $post_id, $revision_id, $before['hash'] );
			return new WP_Error( 'wpagent_elementor_save_failed', __( 'Elementor konnte das Dokument nicht speichern.', 'wp-agent-companion' ), array( 'status' => 500, 'rolled_back' => $rolled_back ) );
		}
		$fresh_document = \Elementor\Plugin::$instance->documents->get( $post_id, false );
		$after = is_object( $fresh_document ) ? wpagent_elementor_document_state( $post_id, $fresh_document ) : null;
		$verified = true === $saved && is_array( $after ) && wpagent_elementor_elements_contain_requested( $after['elements'], $normalized );
		$element_id = is_string( $mutation_result['meta']['element_id'] ?? null ) ? $mutation_result['meta']['element_id'] : '';
		$fresh_element = null;
		if ( $verified && '' !== $element_id ) {
			$fresh_element = wpagent_elementor_locate_element( $after['elements'], $element_id );
			$expect_absent = ! empty( $mutation_result['expect_absent'] );
			$verified = $expect_absent
				? is_wp_error( $fresh_element ) && 'wpagent_elementor_element_not_found' === $fresh_element->get_error_code()
				: is_array( $fresh_element );
		}
		$frontend = $verified ? wpagent_elementor_verify_frontend( $post_id, $after['element_count'] ) : false;
		if ( ! $verified || is_wp_error( $frontend ) ) {
			$rolled_back = wpagent_elementor_restore_revision_internal( $post_id, $revision_id, $before['hash'] );
			return new WP_Error( 'wpagent_elementor_verify_failed', __( 'Die Elementor-Strukturänderung bestand die Rücklese- oder Frontend-Prüfung nicht.', 'wp-agent-companion' ), array( 'status' => 500, 'rolled_back' => $rolled_back, 'revision_id' => $revision_id ) );
		}
		$after['verified'] = true;
		$after['frontend_verified'] = true;
		$after['previous_hash'] = $before['hash'];
		$after['revision_id'] = $revision_id;
		$after['operation'] = $operation;
		$after['changed'] = true;
		$after = array_merge( $after, $mutation_result['meta'] ?? array() );
		if ( is_array( $fresh_element ) ) {
			$after['path'] = $fresh_element['path'];
			$after['element'] = $fresh_element['element'];
		}
		return $after;
	} finally {
		wpagent_elementor_release_lock( $post_id, $lock );
	}
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_create_elementor_element( $input ) {
	$input = is_array( $input ) ? $input : array();
	$target = wpagent_elementor_parse_tree_target( $input );
	if ( is_wp_error( $target ) ) {
		return $target;
	}
	$element = $input['element'] ?? null;
	if ( ! is_array( $element ) || array_is_list( $element ) ) {
		return new WP_Error( 'wpagent_elementor_bad_element', __( 'element muss ein Objekt sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$encoded = wp_json_encode( $element );
	if ( false === $encoded || strlen( $encoded ) > WPAGENT_ELEMENTOR_MAX_BYTES ) {
		return new WP_Error( 'wpagent_elementor_payload_size', __( 'Der neue Elementor-Teilbaum darf höchstens 2 MiB groß sein.', 'wp-agent-companion' ), array( 'status' => 413 ) );
	}
	$request = wpagent_elementor_parse_tree_write_request( $input );
	if ( is_wp_error( $request ) ) {
		return $request;
	}
	return wpagent_elementor_commit_tree_mutation(
		$request['post_id'],
		$request['expected_hash'],
		'create',
		static function ( array $elements, array $_before ) use ( $target, $element ) {
			$ids = wpagent_elementor_tree_ids( $elements );
			if ( is_wp_error( $ids ) ) {
				return $ids;
			}
			$count = 0;
			$prepared = wpagent_elementor_prepare_new_subtree( $element, $ids, 0, $count );
			if ( is_wp_error( $prepared ) ) {
				return $prepared;
			}
			$parent_path = wpagent_elementor_parent_path( $elements, $target['parent_id'] );
			if ( is_wp_error( $parent_path ) ) {
				return $parent_path;
			}
			$path = wpagent_elementor_insert_under_parent( $elements, $parent_path, $target['index'], $prepared );
			if ( is_wp_error( $path ) ) {
				return $path;
			}
			return array( 'elements' => $elements, 'meta' => array( 'element_id' => $prepared['id'], 'path' => $path ) );
		}
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_duplicate_elementor_element( $input ) {
	$input = is_array( $input ) ? $input : array();
	$element_id = is_string( $input['element_id'] ?? null ) ? $input['element_id'] : '';
	if ( ! preg_match( '/^[A-Za-z0-9_-]{1,64}$/', $element_id ) ) {
		return new WP_Error( 'wpagent_elementor_bad_id', __( 'element_id ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$target = wpagent_elementor_parse_tree_target( $input );
	if ( is_wp_error( $target ) ) {
		return $target;
	}
	$request = wpagent_elementor_parse_tree_write_request( $input );
	if ( is_wp_error( $request ) ) {
		return $request;
	}
	return wpagent_elementor_commit_tree_mutation(
		$request['post_id'],
		$request['expected_hash'],
		'duplicate',
		static function ( array $elements, array $_before ) use ( $element_id, $target ) {
			$source = wpagent_elementor_locate_element( $elements, $element_id );
			if ( is_wp_error( $source ) ) {
				return $source;
			}
			$ids = wpagent_elementor_tree_ids( $elements );
			if ( is_wp_error( $ids ) ) {
				return $ids;
			}
			$copy = wpagent_elementor_duplicate_subtree( $source['element'], $ids );
			if ( is_wp_error( $copy ) ) {
				return $copy;
			}
			$parent_path = wpagent_elementor_parent_path( $elements, $target['parent_id'] );
			if ( is_wp_error( $parent_path ) ) {
				return $parent_path;
			}
			$path = wpagent_elementor_insert_under_parent( $elements, $parent_path, $target['index'], $copy );
			if ( is_wp_error( $path ) ) {
				return $path;
			}
			return array( 'elements' => $elements, 'meta' => array( 'element_id' => $copy['id'], 'path' => $path, 'previous_path' => $source['path'] ) );
		}
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_move_elementor_element( $input ) {
	$input = is_array( $input ) ? $input : array();
	$element_id = is_string( $input['element_id'] ?? null ) ? $input['element_id'] : '';
	if ( ! preg_match( '/^[A-Za-z0-9_-]{1,64}$/', $element_id ) ) {
		return new WP_Error( 'wpagent_elementor_bad_id', __( 'element_id ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$target = wpagent_elementor_parse_tree_target( $input );
	if ( is_wp_error( $target ) ) {
		return $target;
	}
	$request = wpagent_elementor_parse_tree_write_request( $input );
	if ( is_wp_error( $request ) ) {
		return $request;
	}
	return wpagent_elementor_commit_tree_mutation(
		$request['post_id'],
		$request['expected_hash'],
		'move',
		static function ( array $elements, array $_before ) use ( $element_id, $target ) {
			$source = wpagent_elementor_locate_element( $elements, $element_id );
			if ( is_wp_error( $source ) ) {
				return $source;
			}
			$parent_path = wpagent_elementor_parent_path( $elements, $target['parent_id'] );
			if ( is_wp_error( $parent_path ) ) {
				return $parent_path;
			}
			if ( null !== $parent_path && wpagent_elementor_path_is_prefix( $source['path'], $parent_path ) ) {
				return new WP_Error( 'wpagent_elementor_cycle', __( 'Ein Elementor-Element kann nicht in sich selbst oder einen Nachfahren verschoben werden.', 'wp-agent-companion' ), array( 'status' => 400 ) );
			}
			$removed = wpagent_elementor_remove_at_path( $elements, $source['path'] );
			if ( is_wp_error( $removed ) ) {
				return $removed;
			}
			$updated_parent_path = wpagent_elementor_parent_path( $elements, $target['parent_id'] );
			if ( is_wp_error( $updated_parent_path ) ) {
				return $updated_parent_path;
			}
			$path = wpagent_elementor_insert_under_parent( $elements, $updated_parent_path, $target['index'], $removed );
			if ( is_wp_error( $path ) ) {
				return $path;
			}
			return array( 'elements' => $elements, 'meta' => array( 'element_id' => $element_id, 'path' => $path, 'previous_path' => $source['path'] ) );
		}
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_delete_elementor_element( $input ) {
	$input = is_array( $input ) ? $input : array();
	$element_id = is_string( $input['element_id'] ?? null ) ? $input['element_id'] : '';
	if ( ! preg_match( '/^[A-Za-z0-9_-]{1,64}$/', $element_id ) ) {
		return new WP_Error( 'wpagent_elementor_bad_id', __( 'element_id ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( true !== ( $input['confirm'] ?? null ) ) {
		return new WP_Error( 'wpagent_elementor_confirmation_required', __( 'Das Löschen eines Elementor-Teilbaums erfordert confirm=true.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$request = wpagent_elementor_parse_tree_write_request( $input );
	if ( is_wp_error( $request ) ) {
		return $request;
	}
	return wpagent_elementor_commit_tree_mutation(
		$request['post_id'],
		$request['expected_hash'],
		'delete',
		static function ( array $elements, array $_before ) use ( $element_id ) {
			$source = wpagent_elementor_locate_element( $elements, $element_id );
			if ( is_wp_error( $source ) ) {
				return $source;
			}
			$removed = wpagent_elementor_remove_at_path( $elements, $source['path'] );
			if ( is_wp_error( $removed ) ) {
				return $removed;
			}
			return array(
				'elements' => $elements,
				'expect_absent' => true,
				'meta' => array( 'element_id' => $element_id, 'previous_path' => $source['path'], 'deleted_element' => $removed ),
			);
		}
	);
}
