<?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 ),
		'delete-meta-box-field-group' => array( 'native' => 'meta-box/delete-field-group', 'permission' => $admin, 'destructive' => 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' ),
		'delete-meta-box-field'       => array( 'native' => 'meta-box/delete-field', 'permission' => $admin, 'destructive' => true, 'handler' => 'fields' ),
		'move-meta-box-field'         => array( 'native' => 'meta-box/move-field', 'permission' => $admin, 'handler' => 'fields' ),
		'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 ),
		'delete-meta-box-post-type'   => array( 'native' => 'meta-box/delete-post-type', 'permission' => $admin, 'destructive' => true, 'handler' => 'definition_delete' ),
		'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 ),
		'delete-meta-box-taxonomy'    => array( 'native' => 'meta-box/delete-taxonomy', 'permission' => $admin, 'destructive' => true, 'handler' => 'definition_delete' ),
		'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' ),
		'delete-meta-box-field-value'     => array( 'native' => 'meta-box/delete-field-value', 'permission' => $edit, 'destructive' => true, 'handler' => 'value' ),
	);
}

/** @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;
}

/** @return array<string,mixed> */
function wpagent_metabox_complete_schema( array $schema ): array {
	if ( ! isset( $schema['type'] ) ) {
		if ( isset( $schema['properties'] ) ) {
			$schema['type'] = 'object';
		} elseif ( isset( $schema['items'] ) ) {
			$schema['type'] = 'array';
		} else {
			$schema['type'] = WPAGENT_MIXED_JSON_TYPES;
		}
	}
	if ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) {
		foreach ( $schema['properties'] as $name => $property ) {
			if ( is_array( $property ) ) {
				$schema['properties'][ $name ] = wpagent_metabox_complete_schema( $property );
			}
		}
	}
	if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) {
		$schema['items'] = wpagent_metabox_complete_schema( $schema['items'] );
	}
	if ( isset( $schema['additionalProperties'] ) && is_array( $schema['additionalProperties'] ) ) {
		$schema['additionalProperties'] = wpagent_metabox_complete_schema( $schema['additionalProperties'] );
	}
	return $schema;
}

/** @return array<string,mixed> */
function wpagent_metabox_proxy_definition( string $slug, array $operation ): array {
	$native      = wpagent_metabox_native_ability( (string) $operation['native'] );
	$input       = is_wp_error( $native ) ? array( 'type' => 'object', 'additionalProperties' => true ) : wpagent_metabox_complete_schema( $native->get_input_schema() );
	$output      = is_wp_error( $native ) ? array( 'type' => WPAGENT_MIXED_JSON_TYPES ) : wpagent_metabox_complete_schema( $native->get_output_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();
	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;
			}
			$native = wpagent_metabox_native_ability( $native_name );
			return is_wp_error( $native ) || true === $native->check_permissions( $input );
		},
		'meta' => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => ! empty( $operation['readonly'] ),
				'destructive' => ! empty( $operation['destructive'] ),
				'idempotent'  => ! empty( $operation['readonly'] ) || str_starts_with( $slug, 'update-' ) || str_starts_with( $slug, 'move-' ),
			),
		),
	);
}

/** @return mixed */
function wpagent_metabox_execute( string $slug, string $native_name, array $operation, array $input ) {
	if ( 'fields' === ( $operation['handler'] ?? '' ) ) {
		return wpagent_metabox_execute_field_operation( $slug, $input );
	}
	if ( 'definition_delete' === ( $operation['handler'] ?? '' ) ) {
		return wpagent_metabox_delete_definition( $slug, $input );
	}
	if ( 'value_format' === ( $operation['handler'] ?? '' ) ) {
		return wpagent_metabox_get_field_value_format( $input );
	}
	if ( 'value' === ( $operation['handler'] ?? '' ) ) {
		return wpagent_metabox_execute_value_operation( $slug, $input );
	}
	$native = wpagent_metabox_native_ability( $native_name );
	if ( is_wp_error( $native ) ) {
		return $native;
	}
	$result = $native->execute( $input );
	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 ) );
	}
	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(),
	);
}
