<?php
/** Safe bridge to the native Meta Box WordPress Abilities. */

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

/** @return array<string,array<string,mixed>> */
function wpagent_metabox_operations(): array {
	$admin = 'wpagent_perm_manage_options';
	$edit  = 'wpagent_perm_edit_posts';
	return array(
		'list-meta-box-field-groups' => array( 'native' => 'meta-box/list-field-groups', 'permission' => $admin, 'readonly' => true ),
		'get-meta-box-field-group'   => array( 'native' => 'meta-box/get-field-group', 'permission' => $admin, 'readonly' => true ),
		'create-meta-box-field-group' => array( 'native' => 'meta-box/create-field-group', 'permission' => $admin ),
		'update-meta-box-field-group' => array( 'native' => 'meta-box/update-field-group', 'permission' => $admin, 'remote_manual_only' => true ),
		'delete-meta-box-field-group' => array( 'native' => 'meta-box/delete-field-group', 'permission' => $admin, 'destructive' => true, 'remote_manual_only' => true ),
		'list-meta-box-fields'        => array( 'native' => 'meta-box/list-fields', 'permission' => $admin, 'readonly' => true, 'handler' => 'fields' ),
		'get-meta-box-field'          => array( 'native' => 'meta-box/get-field', 'permission' => $admin, 'readonly' => true, 'handler' => 'fields' ),
		'create-meta-box-field'       => array( 'native' => 'meta-box/create-field', 'permission' => $admin, 'handler' => 'fields' ),
		'update-meta-box-field'       => array( 'native' => 'meta-box/update-field', 'permission' => $admin, 'handler' => 'fields', 'remote_manual_only' => true ),
		'delete-meta-box-field'       => array( 'native' => 'meta-box/delete-field', 'permission' => $admin, 'destructive' => true, 'handler' => 'fields', 'remote_manual_only' => true ),
		'move-meta-box-field'         => array( 'native' => 'meta-box/move-field', 'permission' => $admin, 'handler' => 'fields', 'remote_manual_only' => true ),
		'list-meta-box-post-types'    => array( 'native' => 'meta-box/get-post-types', 'permission' => $admin, 'readonly' => true ),
		'get-meta-box-post-type'      => array( 'native' => 'meta-box/get-post-types', 'permission' => $admin, 'readonly' => true ),
		'create-meta-box-post-type'   => array( 'native' => 'meta-box/create-post-type', 'permission' => $admin ),
		'update-meta-box-post-type'   => array( 'native' => 'meta-box/update-post-type', 'permission' => $admin, 'remote_manual_only' => true ),
		'delete-meta-box-post-type'   => array( 'native' => 'meta-box/delete-post-type', 'permission' => $admin, 'destructive' => true, 'handler' => 'definition_delete', 'remote_manual_only' => true ),
		'list-meta-box-taxonomies'    => array( 'native' => 'meta-box/get-taxonomies', 'permission' => $admin, 'readonly' => true ),
		'get-meta-box-taxonomy'       => array( 'native' => 'meta-box/get-taxonomies', 'permission' => $admin, 'readonly' => true ),
		'create-meta-box-taxonomy'    => array( 'native' => 'meta-box/create-taxonomy', 'permission' => $admin ),
		'update-meta-box-taxonomy'    => array( 'native' => 'meta-box/update-taxonomy', 'permission' => $admin, 'remote_manual_only' => true ),
		'delete-meta-box-taxonomy'    => array( 'native' => 'meta-box/delete-taxonomy', 'permission' => $admin, 'destructive' => true, 'handler' => 'definition_delete', 'remote_manual_only' => true ),
		'get-meta-box-field-value-format' => array( 'native' => 'meta-box/get-field-value-format', 'permission' => $edit, 'readonly' => true, 'handler' => 'value_format' ),
		'get-meta-box-field-value'        => array( 'native' => 'meta-box/get-field-value', 'permission' => $edit, 'readonly' => true, 'handler' => 'value' ),
		'update-meta-box-field-value'     => array( 'native' => 'meta-box/update-field-value', 'permission' => $edit, 'handler' => 'value', 'remote_manual_only' => true ),
		'delete-meta-box-field-value'     => array( 'native' => 'meta-box/delete-field-value', 'permission' => $edit, 'destructive' => true, 'handler' => 'value', 'remote_manual_only' => true ),
	);
}

/** @return WP_Error|null */
function wpagent_metabox_remote_mutation_unavailable( string $slug, array $operation ) {
	if ( empty( $operation['remote_manual_only'] ) ) {
		return null;
	}
	return new WP_Error(
		'wpagent_metabox_remote_mutation_unavailable',
		__( 'Diese Meta-Box-Änderung bleibt im WordPress-Admin manuell, weil Meta Box dafür keine belastbare versionierte Compare-and-Swap-Prüfung bereitstellt.', 'wp-agent-companion' ),
		array(
			'status'                 => 409,
			'manual_action_required' => true,
			'operation'              => $slug,
		)
	);
}

/** @return WP_Ability|WP_Error */
function wpagent_metabox_native_ability( string $name ) {
	$ability = wpagent_companion_get_registered_ability( $name );
	if ( ! $ability instanceof WP_Ability ) {
		return new WP_Error(
			'wpagent_metabox_missing',
			__( 'Meta Box 5.14 oder neuer und die für diese Operation benötigte freie Erweiterung sind nicht aktiv.', 'wp-agent-companion' ),
			array( 'status' => 409 )
		);
	}
	$meta = $ability->get_meta();
	if ( ! is_array( $meta ) || true !== ( $meta['mcp']['public'] ?? null ) ) {
		return new WP_Error( 'wpagent_metabox_not_public', __( 'Meta Box hat diese native Ability nicht für MCP freigegeben.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	return $ability;
}

define( 'WPAGENT_METABOX_PROXY_MAX_DEPTH', 8 );
define( 'WPAGENT_METABOX_PROXY_MAX_PROPERTIES', 50 );
define( 'WPAGENT_METABOX_PROXY_MAX_ITEMS', 100 );
define( 'WPAGENT_METABOX_PROXY_MAX_TEXT_LENGTH', 10000 );

/** @return WP_Error */
function wpagent_metabox_schema_unavailable( string $native_name ) {
	return new WP_Error(
		'wpagent_metabox_schema_unavailable',
		/* translators: %s: native Meta Box Ability name. */
		sprintf( __( 'Die native Meta-Box-Ability %s veröffentlicht kein vollständig begrenztes Schema. WPAgently leitet deshalb weder Eingaben noch Provider-Aufrufe weiter.', 'wp-agent-companion' ), $native_name ),
		array( 'status' => 409, 'manual_action_required' => true )
	);
}

/** @return array<string,mixed> */
function wpagent_metabox_unavailable_schema(): array {
	return array(
		'type' => 'object',
		'properties' => array(),
		'required' => array(),
		'maxProperties' => 0,
		'additionalProperties' => false,
	);
}

function wpagent_metabox_schema_integer( $value, int $minimum, int $maximum ): ?int {
	return is_int( $value ) && $value >= $minimum && $value <= $maximum ? $value : null;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_complete_schema( array $schema, int $depth = 0 ) {
	if ( $depth > WPAGENT_METABOX_PROXY_MAX_DEPTH || array_is_list( $schema ) ) {
		return wpagent_metabox_schema_unavailable( 'schema' );
	}
	foreach ( array( '$ref', 'oneOf', 'anyOf', 'allOf', 'not', 'if', 'then', 'else', 'patternProperties', 'unevaluatedProperties', 'contains', 'additionalItems' ) as $unsupported ) {
		if ( array_key_exists( $unsupported, $schema ) ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
	}
	$type = $schema['type'] ?? ( isset( $schema['properties'] ) ? 'object' : ( isset( $schema['items'] ) ? 'array' : null ) );
	if ( ! is_string( $type ) || ! in_array( $type, array( 'object', 'array', 'string', 'integer', 'number', 'boolean', 'null' ), true ) ) {
		return wpagent_metabox_schema_unavailable( 'schema' );
	}
	if ( 'object' === $type ) {
		if ( isset( $schema['additionalProperties'] ) && false !== $schema['additionalProperties'] ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		$properties = $schema['properties'] ?? array();
		if ( ! is_array( $properties ) || array_is_list( $properties ) || count( $properties ) > WPAGENT_METABOX_PROXY_MAX_PROPERTIES ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		$normalized = array();
		foreach ( $properties as $name => $property ) {
			if ( ! is_string( $name ) || '' === $name || strlen( $name ) > 100 || 1 === preg_match( '/[\x00-\x1F\x7F]/', $name ) || ! is_array( $property ) ) {
				return wpagent_metabox_schema_unavailable( 'schema' );
			}
			$property = wpagent_metabox_complete_schema( $property, $depth + 1 );
			if ( is_wp_error( $property ) ) {
				return $property;
			}
			$normalized[ $name ] = $property;
		}
		$required = $schema['required'] ?? array();
		if ( ! is_array( $required ) || ! array_is_list( $required ) || count( $required ) > count( $normalized ) ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		foreach ( $required as $name ) {
			if ( ! is_string( $name ) || ! array_key_exists( $name, $normalized ) ) {
				return wpagent_metabox_schema_unavailable( 'schema' );
			}
		}
		$native_max = array_key_exists( 'maxProperties', $schema ) ? wpagent_metabox_schema_integer( $schema['maxProperties'], 0, WPAGENT_METABOX_PROXY_MAX_PROPERTIES ) : count( $normalized );
		if ( null === $native_max || $native_max < count( $required ) ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		return array( 'type' => 'object', 'properties' => $normalized, 'required' => array_values( array_unique( $required ) ), 'maxProperties' => min( $native_max, count( $normalized ) ), 'additionalProperties' => false );
	}
	if ( 'array' === $type ) {
		if ( ! isset( $schema['items'] ) || ! is_array( $schema['items'] ) ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		$items = wpagent_metabox_complete_schema( $schema['items'], $depth + 1 );
		if ( is_wp_error( $items ) ) {
			return $items;
		}
		$native_max = array_key_exists( 'maxItems', $schema ) ? wpagent_metabox_schema_integer( $schema['maxItems'], 0, WPAGENT_METABOX_PROXY_MAX_ITEMS ) : WPAGENT_METABOX_PROXY_MAX_ITEMS;
		$native_min = array_key_exists( 'minItems', $schema ) ? wpagent_metabox_schema_integer( $schema['minItems'], 0, WPAGENT_METABOX_PROXY_MAX_ITEMS ) : 0;
		if ( null === $native_max || null === $native_min || $native_min > $native_max ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		return array( 'type' => 'array', 'items' => $items, 'minItems' => $native_min, 'maxItems' => $native_max );
	}
	if ( 'string' === $type ) {
		$maximum = array_key_exists( 'maxLength', $schema ) ? wpagent_metabox_schema_integer( $schema['maxLength'], 0, WPAGENT_METABOX_PROXY_MAX_TEXT_LENGTH ) : WPAGENT_METABOX_PROXY_MAX_TEXT_LENGTH;
		$minimum = array_key_exists( 'minLength', $schema ) ? wpagent_metabox_schema_integer( $schema['minLength'], 0, WPAGENT_METABOX_PROXY_MAX_TEXT_LENGTH ) : 0;
		if ( null === $maximum || null === $minimum || $minimum > $maximum || ( isset( $schema['pattern'] ) && ( ! is_string( $schema['pattern'] ) || strlen( $schema['pattern'] ) > 256 ) ) ) {
			return wpagent_metabox_schema_unavailable( 'schema' );
		}
		$result = array( 'type' => 'string', 'minLength' => $minimum, 'maxLength' => $maximum );
		if ( isset( $schema['pattern'] ) ) {
			$result['pattern'] = $schema['pattern'];
		}
		return $result;
	}
	if ( in_array( $type, array( 'integer', 'number' ), true ) ) {
		return array( 'type' => $type, 'minimum' => -2147483648, 'maximum' => 2147483647 );
	}
	return array( 'type' => $type );
}

/** @return array{ability:WP_Ability,input:array<string,mixed>,output:array<string,mixed>}|WP_Error */
function wpagent_metabox_native_contract( string $native_name ) {
	$native = wpagent_metabox_native_ability( $native_name );
	if ( is_wp_error( $native ) ) {
		return $native;
	}
	$input = wpagent_metabox_complete_schema( $native->get_input_schema() );
	$output = wpagent_metabox_complete_schema( $native->get_output_schema() );
	if ( is_wp_error( $input ) || is_wp_error( $output ) ) {
		return wpagent_metabox_schema_unavailable( $native_name );
	}
	return array( 'ability' => $native, 'input' => $input, 'output' => $output );
}

/** @return true|WP_Error */
function wpagent_metabox_validate_proxy_value( $value, array $schema, string $direction ) {
	if ( ! function_exists( 'rest_validate_value_from_schema' ) ) {
		return new WP_Error(
			'wpagent_metabox_schema_unavailable',
			__( 'WordPress kann das begrenzte Meta-Box-Schema in dieser Laufzeit nicht prüfen.', 'wp-agent-companion' ),
			array( 'status' => 409, 'manual_action_required' => true )
		);
	}
	$validated = rest_validate_value_from_schema( $value, $schema, 'meta_box_' . $direction );
	if ( ! is_wp_error( $validated ) ) {
		return true;
	}
	return new WP_Error(
		'input' === $direction ? 'wpagent_metabox_proxy_input_invalid' : 'wpagent_metabox_proxy_output_invalid',
		'input' === $direction
			? __( 'Die Meta-Box-Eingabe entspricht nicht dem begrenzten nativen Schema.', 'wp-agent-companion' )
			: __( 'Meta Box hat eine Antwort außerhalb des begrenzten nativen Schemas zurückgegeben. Es wurde kein unbeschränktes Provider-Ergebnis weitergegeben.', 'wp-agent-companion' ),
		array( 'status' => 'input' === $direction ? 400 : 500 )
	);
}

/** @return array<string,mixed> */
function wpagent_metabox_proxy_definition( string $slug, array $operation ): array {
	$contract    = wpagent_metabox_native_contract( (string) $operation['native'] );
	$native      = is_array( $contract ) ? $contract['ability'] : wpagent_metabox_native_ability( (string) $operation['native'] );
	$input       = is_array( $contract ) ? $contract['input'] : wpagent_metabox_unavailable_schema();
	$output      = is_array( $contract ) ? $contract['output'] : wpagent_metabox_unavailable_schema();
	$native_name = (string) $operation['native'];
	$label       = is_wp_error( $native ) ? str_replace( '-', ' ', $slug ) : $native->get_label();
	$description = is_wp_error( $native ) ? __( 'Verwendet die native Meta-Box-API mit den WPAgently-Sicherheits- und Berechtigungsgrenzen.', 'wp-agent-companion' ) : $native->get_description();
	if ( ! empty( $operation['remote_manual_only'] ) ) {
		$description = __( 'Diese Meta-Box-Änderung ist für Remote-Ausführung deaktiviert und muss im WordPress-Admin vorgenommen werden, weil Meta Box keine belastbare versionierte Compare-and-Swap-Prüfung bereitstellt.', 'wp-agent-companion' );
	}
	return array(
		'label'       => $label,
		'description' => $description,
		'category'    => 'wp-agent',
		'input_schema' => $input,
		'output_schema' => $output,
		'execute_callback' => static function ( $input ) use ( $slug, $native_name, $operation ) {
			return wpagent_metabox_execute( $slug, $native_name, $operation, is_array( $input ) ? $input : array() );
		},
		'permission_callback' => static function ( $input ) use ( $native_name, $operation ): bool {
			$callback = (string) $operation['permission'];
			if ( ! is_callable( $callback ) || true !== call_user_func( $callback, $input ) ) {
				return false;
			}
			if ( ! empty( $operation['remote_manual_only'] ) ) {
				return true;
			}
			$contract = wpagent_metabox_native_contract( $native_name );
			return is_wp_error( $contract ) || true === $contract['ability']->check_permissions( $input );
		},
		'meta' => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => ! empty( $operation['readonly'] ),
				'destructive' => ! empty( $operation['destructive'] ),
				'idempotent'  => empty( $operation['remote_manual_only'] ) && ( ! empty( $operation['readonly'] ) || str_starts_with( $slug, 'update-' ) || str_starts_with( $slug, 'move-' ) ),
				'manual_only' => ! empty( $operation['remote_manual_only'] ),
			),
		),
	);
}

/** @return mixed */
function wpagent_metabox_execute( string $slug, string $native_name, array $operation, array $input ) {
	$unavailable = wpagent_metabox_remote_mutation_unavailable( $slug, $operation );
	if ( $unavailable instanceof WP_Error ) {
		return $unavailable;
	}
	$contract = wpagent_metabox_native_contract( $native_name );
	if ( is_wp_error( $contract ) ) {
		return $contract;
	}
	$validated = wpagent_metabox_validate_proxy_value( $input, $contract['input'], 'input' );
	if ( is_wp_error( $validated ) ) {
		return $validated;
	}
	if ( 'fields' === ( $operation['handler'] ?? '' ) ) {
		$result = wpagent_metabox_execute_field_operation( $slug, $input );
	} elseif ( 'definition_delete' === ( $operation['handler'] ?? '' ) ) {
		$result = wpagent_metabox_delete_definition( $slug, $input );
	} elseif ( 'value_format' === ( $operation['handler'] ?? '' ) ) {
		$result = wpagent_metabox_get_field_value_format( $input );
	} elseif ( 'value' === ( $operation['handler'] ?? '' ) ) {
		$result = wpagent_metabox_execute_value_operation( $slug, $input );
	} else {
		$result = $contract['ability']->execute( $input );
	}
	if ( is_wp_error( $result ) ) {
		if ( 'ability_invalid_output' === $result->get_error_code() ) {
			return new WP_Error(
				'wpagent_metabox_proxy_output_invalid',
				__( 'Meta Box hat eine Antwort außerhalb des begrenzten nativen Schemas zurückgegeben. Es wurde kein unbeschränktes Provider-Ergebnis weitergegeben.', 'wp-agent-companion' ),
				array( 'status' => 500 )
			);
		}
		return $result;
	}
	if ( is_array( $result ) && array_key_exists( 'success', $result ) && ! $result['success'] ) {
		return new WP_Error( 'wpagent_metabox_native_failed', sanitize_text_field( (string) ( $result['message'] ?? __( 'Meta Box konnte die Änderung nicht speichern.', 'wp-agent-companion' ) ) ), array( 'status' => 500 ) );
	}
	$validated = wpagent_metabox_validate_proxy_value( $result, $contract['output'], 'output' );
	if ( is_wp_error( $validated ) ) {
		return $validated;
	}
	return $result;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_execute_value_operation( string $slug, array $input ) {
	if ( ! class_exists( 'MetaBox\\Abilities\\Abilities' ) ) {
		return new WP_Error( 'wpagent_metabox_missing', __( 'Meta Box 5.14 oder neuer ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$methods = array(
		'get-meta-box-field-value'    => 'get_field_value',
		'update-meta-box-field-value' => 'update_field_value',
		'delete-meta-box-field-value' => 'delete_field_value',
	);
	$method = $methods[ $slug ] ?? '';
	if ( '' === $method ) {
		return new WP_Error( 'wpagent_metabox_operation_unknown', __( 'Unbekannte Meta-Box-Feldoperation.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$result = ( new MetaBox\Abilities\Abilities() )->{$method}( $input );
	if ( array_key_exists( 'success', $result ) && ! $result['success'] ) {
		return new WP_Error( 'wpagent_metabox_native_failed', __( 'Meta Box konnte die Änderung nicht speichern.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	return $result;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_get_field_value_format( array $input ) {
	if ( ! class_exists( 'MetaBox\\Abilities\\Abilities' ) ) {
		return new WP_Error( 'wpagent_metabox_missing', __( 'Meta Box 5.14 oder neuer ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$result = ( new MetaBox\Abilities\Abilities() )->get_field_value_format( $input );
	if ( ! is_array( $result ) ) {
		return new WP_Error( 'wpagent_metabox_format_failed', __( 'Meta Box konnte das Feldformat nicht bestimmen.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	// Meta Box 5.14 returns field_id although its public output schema forbids it.
	unset( $result['field_id'] );
	return $result;
}

/** @return WP_Post|WP_Error */
function wpagent_metabox_field_group( $id ) {
	$post = get_post( absint( $id ) );
	if ( ! $post instanceof WP_Post || 'meta-box' !== $post->post_type ) {
		return new WP_Error( 'wpagent_metabox_group_not_found', __( 'Meta-Box-Feldgruppe nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	return $post;
}

/** @return int|null */
function wpagent_metabox_field_index( array $fields, string $field_id ): ?int {
	foreach ( $fields as $index => $field ) {
		$id = is_array( $field ) ? (string) ( $field['id'] ?? $field['_id'] ?? '' ) : '';
		if ( hash_equals( $id, $field_id ) ) {
			return (int) $index;
		}
	}
	return null;
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_normalize_field( array $field ) {
	if ( ! class_exists( 'MBBParser\\Unparsers\\Field' ) ) {
		return new WP_Error( 'wpagent_metabox_builder_missing', __( 'MB Builder ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	try {
		$unparser = new MBBParser\Unparsers\Field( $field );
		$unparser->unparse();
		$normalized = $unparser->get_settings();
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_metabox_field_invalid', __( 'Die Meta-Box-Felddefinition ist ungültig.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$id   = is_array( $normalized ) ? (string) ( $normalized['id'] ?? '' ) : '';
	$type = is_array( $normalized ) ? (string) ( $normalized['type'] ?? '' ) : '';
	if ( ! preg_match( '/^[A-Za-z_][A-Za-z0-9_-]{0,190}$/', $id ) || ! preg_match( '/^[a-z][a-z0-9_-]{0,63}$/', $type ) ) {
		return new WP_Error( 'wpagent_metabox_field_invalid', __( 'Das Feld benötigt eine sichere ID und einen gültigen Meta-Box-Feldtyp.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	return $normalized;
}

/** @param array<string,array{exists:bool,value:mixed}> $snapshot */
function wpagent_metabox_restore_field_snapshot( int $post_id, array $snapshot ): bool {
	foreach ( $snapshot as $key => $state ) {
		if ( $state['exists'] ) {
			update_post_meta( $post_id, $key, $state['value'] );
		} else {
			delete_post_meta( $post_id, $key );
		}
	}
	foreach ( $snapshot as $key => $state ) {
		$exists = metadata_exists( 'post', $post_id, $key );
		if ( $exists !== $state['exists'] || ( $exists && get_post_meta( $post_id, $key, true ) !== $state['value'] ) ) {
			return false;
		}
	}
	return true;
}

/** @return true|WP_Error */
function wpagent_metabox_save_fields( WP_Post $post, array $fields, array $settings ) {
	if ( ! class_exists( 'MBB\\RestApi\\Save' ) || ! class_exists( 'MBBParser\\Parsers\\Base' ) ) {
		return new WP_Error( 'wpagent_metabox_builder_missing', __( 'MB Builder ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$keys     = array( 'fields', 'settings', 'meta_box' );
	$snapshot = array();
	foreach ( $keys as $key ) {
		$snapshot[ $key ] = array( 'exists' => metadata_exists( 'post', $post->ID, $key ), 'value' => get_post_meta( $post->ID, $key, true ) );
	}
	try {
		$parser = new MBBParser\Parsers\Base();
		$parser->set_settings( array_values( $fields ) )->parse_boolean_values()->parse_numeric_values();
		$expected_fields = $parser->get_settings();
		$parser->set_settings( $settings )->parse_boolean_values()->parse_numeric_values();
		$expected_settings = $parser->get_settings();
		$meta_box_parser   = MBB\RestApi\Save::parse( $post, array_values( $fields ), $settings );
		$expected_meta_box = $meta_box_parser->get_settings();
		$actual_fields   = get_post_meta( $post->ID, 'fields', true );
		$actual_settings = get_post_meta( $post->ID, 'settings', true );
		$actual_meta_box = get_post_meta( $post->ID, 'meta_box', true );
		if (
			! is_array( $actual_fields ) ||
			! is_array( $actual_settings ) ||
			! is_array( $actual_meta_box ) ||
			wp_json_encode( array_values( $actual_fields ) ) !== wp_json_encode( array_values( $expected_fields ) ) ||
			wp_json_encode( $actual_settings ) !== wp_json_encode( $expected_settings ) ||
			wp_json_encode( $actual_meta_box ) !== wp_json_encode( $expected_meta_box )
		) {
			throw new RuntimeException( 'Meta Box field read-back mismatch.' );
		}
		return true;
	} catch ( Throwable $error ) {
		if ( ! wpagent_metabox_restore_field_snapshot( $post->ID, $snapshot ) ) {
			return new WP_Error( 'wpagent_metabox_field_rollback_failed', __( 'Die Feldänderung konnte nicht verifiziert und der vorherige Zustand nicht vollständig wiederhergestellt werden. Prüfe die Feldgruppe sofort manuell.', 'wp-agent-companion' ), array( 'status' => 500 ) );
		}
		return new WP_Error( 'wpagent_metabox_field_save_failed', __( 'Die Feldänderung konnte nicht exakt verifiziert werden und wurde zurückgerollt.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
}

function wpagent_metabox_field_lock_name( int $post_id ): string {
	return 'wp_agent_metabox_fields_lock_' . hash( 'sha256', (string) $post_id );
}

/** @return string|WP_Error */
function wpagent_metabox_acquire_field_lock( int $post_id ) {
	$option = wpagent_metabox_field_lock_name( $post_id );
	$token  = wpagent_companion_acquire_option_lock( $option, 300 );
	if ( is_string( $token ) ) {
		return $token;
	}
	return new WP_Error( 'wpagent_metabox_fields_busy', __( 'Diese Meta-Box-Feldgruppe wird gerade geändert. Versuche es gleich erneut.', 'wp-agent-companion' ), array( 'status' => 409 ) );
}

function wpagent_metabox_release_field_lock( int $post_id, string $token ): void {
	wpagent_companion_release_option_lock( wpagent_metabox_field_lock_name( $post_id ), $token );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_execute_field_operation( string $slug, array $input ) {
	$post = wpagent_metabox_field_group( $input['field_group_id'] ?? 0 );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	if ( in_array( $slug, array( 'list-meta-box-fields', 'get-meta-box-field' ), true ) ) {
		return wpagent_metabox_execute_field_operation_locked( $slug, $input, $post );
	}
	$lock = wpagent_metabox_acquire_field_lock( $post->ID );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		return wpagent_metabox_execute_field_operation_locked( $slug, $input, $post );
	} finally {
		wpagent_metabox_release_field_lock( $post->ID, $lock );
	}
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_execute_field_operation_locked( string $slug, array $input, WP_Post $post ) {
	$fields   = get_post_meta( $post->ID, 'fields', true );
	$settings = get_post_meta( $post->ID, 'settings', true );
	$fields   = is_array( $fields ) ? array_values( $fields ) : array();
	$settings = is_array( $settings ) ? $settings : array();
	if ( 'list-meta-box-fields' === $slug ) {
		return array( 'fields' => $fields, 'settings' => $settings );
	}
	$field_id = is_string( $input['field_id'] ?? null ) ? $input['field_id'] : '';
	$index    = '' === $field_id ? null : wpagent_metabox_field_index( $fields, $field_id );
	if ( 'get-meta-box-field' === $slug ) {
		return null === $index ? new WP_Error( 'wpagent_metabox_field_not_found', __( 'Meta-Box-Feld nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) ) : array( 'field' => $fields[ $index ] );
	}
	if ( 'create-meta-box-field' === $slug ) {
		$field = wpagent_metabox_normalize_field( is_array( $input['field'] ?? null ) ? $input['field'] : array() );
		if ( is_wp_error( $field ) ) {
			return $field;
		}
		if ( null !== wpagent_metabox_field_index( $fields, (string) $field['id'] ) ) {
			return new WP_Error( 'wpagent_metabox_field_exists', __( 'Eine Felddefinition mit dieser ID existiert bereits.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$fields[] = $field;
	} elseif ( null === $index ) {
		return new WP_Error( 'wpagent_metabox_field_not_found', __( 'Meta-Box-Feld nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	} elseif ( 'update-meta-box-field' === $slug ) {
		$submitted = is_array( $input['field'] ?? null ) ? $input['field'] : array();
		if ( empty( $submitted['id'] ) ) {
			$submitted['id'] = $field_id;
		}
		$field = wpagent_metabox_normalize_field( $submitted );
		if ( is_wp_error( $field ) ) {
			return $field;
		}
		$collision = wpagent_metabox_field_index( $fields, (string) $field['id'] );
		if ( null !== $collision && $collision !== $index ) {
			return new WP_Error( 'wpagent_metabox_field_exists', __( 'Eine andere Felddefinition verwendet bereits die neue ID.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$fields[ $index ] = array_replace( $fields[ $index ], $field );
	} elseif ( 'delete-meta-box-field' === $slug ) {
		array_splice( $fields, $index, 1 );
	} elseif ( 'move-meta-box-field' === $slug ) {
		$before = is_string( $input['before'] ?? null ) ? $input['before'] : '';
		$after  = is_string( $input['after'] ?? null ) ? $input['after'] : '';
		if ( ( '' !== $before && '' !== $after ) || $before === $field_id || $after === $field_id ) {
			return new WP_Error( 'wpagent_metabox_move_invalid', __( 'Gib genau ein anderes Zielfeld in before oder after an.', 'wp-agent-companion' ), array( 'status' => 400 ) );
		}
		$target_id = '' !== $before ? $before : $after;
		$target    = '' === $target_id ? count( $fields ) : wpagent_metabox_field_index( $fields, $target_id );
		if ( null === $target ) {
			return new WP_Error( 'wpagent_metabox_field_not_found', __( 'Meta-Box-Zielfeld nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
		}
		$field = $fields[ $index ];
		array_splice( $fields, $index, 1 );
		if ( $target > $index ) {
			--$target;
		}
		if ( '' !== $after ) {
			++$target;
		}
		array_splice( $fields, $target, 0, array( $field ) );
	} else {
		return new WP_Error( 'wpagent_metabox_operation_unknown', __( 'Unbekannte Meta-Box-Feldoperation.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$saved = wpagent_metabox_save_fields( $post, $fields, $settings );
	if ( is_wp_error( $saved ) ) {
		return $saved;
	}
	return array( 'success' => true, 'message' => __( 'Meta-Box-Feldänderung gespeichert und verifiziert.', 'wp-agent-companion' ) );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_metabox_delete_definition( string $slug, array $input ) {
	$id        = absint( $input['id'] ?? 0 );
	$post_type = str_contains( $slug, 'taxonomy' ) ? 'mb-taxonomy' : 'mb-post-type';
	$post      = get_post( $id );
	if ( ! $post instanceof WP_Post || $post_type !== $post->post_type ) {
		return new WP_Error( 'wpagent_metabox_definition_not_found', __( 'Meta-Box-Definition nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	$get_name = 'mb-taxonomy' === $post_type ? 'meta-box/get-taxonomies' : 'meta-box/get-post-types';
	$native   = wpagent_metabox_native_ability( $get_name );
	$previous = is_wp_error( $native ) ? array() : $native->execute( array( 'id' => $id ) );
	$deleted  = wp_delete_post( $id, ! empty( $input['force'] ) );
	if ( ! $deleted ) {
		return new WP_Error( 'wpagent_metabox_delete_failed', __( 'Die Meta-Box-Definition konnte nicht gelöscht werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	return array( 'deleted' => true, 'previous' => is_array( $previous ) ? ( $previous[0] ?? array() ) : array() );
}

/** @return array<string,mixed> */
function wpagent_ability_get_meta_box_status(): array {
	return array(
		'label'       => __( 'Meta-Box-Status lesen', 'wp-agent-companion' ),
		'description' => __( 'Prüft Versionen und native WordPress-Abilities der aktiven Meta-Box-Installation.', 'wp-agent-companion' ),
		'category'    => 'wp-agent',
		'input_schema' => array( 'type' => 'object', 'additionalProperties' => false ),
		'output_schema' => array(
			'type' => 'object',
			'properties' => array(
				'available' => array( 'type' => 'boolean' ),
				'meta_box_version' => array( 'type' => 'string' ),
				'builder_version' => array( 'type' => 'string' ),
				'native_ability_count' => array( 'type' => 'integer' ),
				'settings_page_available' => array( 'type' => 'boolean' ),
			),
			'required' => array( 'available', 'meta_box_version', 'builder_version', 'native_ability_count', 'settings_page_available' ),
			'additionalProperties' => false,
		),
		'execute_callback' => 'wpagent_exec_get_meta_box_status',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed> */
function wpagent_exec_get_meta_box_status(): array {
	$count = 0;
	if ( function_exists( 'wp_get_abilities' ) ) {
		foreach ( array_keys( wp_get_abilities() ) as $name ) {
			if ( is_string( $name ) && str_starts_with( $name, 'meta-box/' ) ) {
				++$count;
			}
		}
	}
	return array(
		'available' => defined( 'RWMB_VER' ) && version_compare( RWMB_VER, '5.14.0', '>=' ),
		'meta_box_version' => defined( 'RWMB_VER' ) ? (string) RWMB_VER : '',
		'builder_version' => defined( 'MBB_VER' ) ? (string) MBB_VER : '',
		'native_ability_count' => $count,
		'settings_page_available' => function_exists( 'wpagent_metabox_settings_page_available' ) && wpagent_metabox_settings_page_available(),
	);
}
