<?php
/** Read-only abilities for bounded Pods Settings, groups and core extensions. */

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

/** @return array<string,mixed> */
function wpagent_pods_free_list_input_schema( bool $allow_pod_name = false ): array {
	$properties = array(
		'search' => array( 'type' => 'string', 'maxLength' => WPAGENT_PODS_FREE_MAX_SEARCH_BYTES ),
		'page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => WPAGENT_PODS_FREE_MAX_ITEMS, 'default' => 1 ),
		'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => WPAGENT_PODS_FREE_MAX_PER_PAGE, 'default' => 20 ),
	);
	if ( $allow_pod_name ) {
		$properties['pod_name'] = array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_]{0,63}$' );
	}
	return array( 'type' => 'object', 'properties' => $properties, 'additionalProperties' => false );
}

/** @return array<string,mixed> */
function wpagent_pods_free_get_input_schema( bool $group = false ): array {
	$properties = array(
		'name' => array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_]{0,63}$' ),
		'max_fields' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => WPAGENT_PODS_FREE_MAX_FIELDS, 'default' => 20 ),
	);
	if ( $group ) {
		$properties['pod_name'] = array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_]{0,63}$' );
		return array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'pod_name', 'name' ), 'additionalProperties' => false );
	}
	return array( 'type' => 'object', 'properties' => $properties, 'required' => array( 'name' ), 'additionalProperties' => false );
}

function wpagent_ability_list_pods_settings(): array {
	return array(
		'label' => __( 'Pods-Einstellungen auflisten', 'wp-agent-companion' ),
		'description' => __( 'Listet native Pods-Einstellungsdefinitionen ohne Optionswerte. Die Ausgabe enthält ausschließlich begrenzte Feld- und Menükonfigurationen.', 'wp-agent-companion' ),
		'category' => 'wp-agent', 'input_schema' => wpagent_pods_free_list_input_schema(),
		'output_schema' => wpagent_pods_free_paged_schema( 'settings', wpagent_pods_free_pod_output_schema() ),
		'execute_callback' => 'wpagent_exec_list_pods_settings', 'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_get_pods_settings(): array {
	return array(
		'label' => __( 'Pods-Einstellungen lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest eine native Pods-Einstellungsdefinition einschließlich einer begrenzten Feldliste. Gespeicherte Einstellungen und Optionswerte bleiben ausgeschlossen.', 'wp-agent-companion' ),
		'category' => 'wp-agent', 'input_schema' => wpagent_pods_free_get_input_schema(), 'output_schema' => wpagent_pods_free_pod_output_schema(),
		'execute_callback' => 'wpagent_exec_get_pods_settings', 'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_list_pods_field_groups(): array {
	return array(
		'label' => __( 'Pods-Feldgruppen auflisten', 'wp-agent-companion' ),
		'description' => __( 'Listet native Pods-Feldgruppen und ihre begrenzten Definitionen. Feldwerte, Beziehungen und Mediendaten werden nicht gelesen.', 'wp-agent-companion' ),
		'category' => 'wp-agent', 'input_schema' => wpagent_pods_free_list_input_schema( true ),
		'output_schema' => wpagent_pods_free_paged_schema( 'groups', wpagent_pods_free_group_output_schema() ),
		'execute_callback' => 'wpagent_exec_list_pods_field_groups', 'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_get_pods_field_group(): array {
	return array(
		'label' => __( 'Pods-Feldgruppe lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest eine native Pods-Feldgruppe mit einer begrenzten Liste von Felddefinitionen und einem Konflikt-Hash. Feldwerte bleiben ausgeschlossen.', 'wp-agent-companion' ),
		'category' => 'wp-agent', 'input_schema' => wpagent_pods_free_get_input_schema( true ), 'output_schema' => wpagent_pods_free_group_output_schema(),
		'execute_callback' => 'wpagent_exec_get_pods_field_group', 'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_list_pods_object_extensions(): array {
	return array(
		'label' => __( 'Pods-Objekterweiterungen auflisten', 'wp-agent-companion' ),
		'description' => __( 'Listet native Pods-Erweiterungen für integrierte WordPress-Objekte. Es werden nur Definitionen und keine Objekt- oder Feldwerte ausgegeben.', 'wp-agent-companion' ),
		'category' => 'wp-agent', 'input_schema' => wpagent_pods_free_list_input_schema(),
		'output_schema' => wpagent_pods_free_paged_schema( 'extensions', wpagent_pods_free_pod_output_schema() ),
		'execute_callback' => 'wpagent_exec_list_pods_object_extensions', 'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

function wpagent_ability_get_pods_object_extension(): array {
	return array(
		'label' => __( 'Pods-Objekterweiterung lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest eine native Pods-Erweiterung eines integrierten WordPress-Objekts. Feldwerte sowie nicht unterstützte Beziehungs- und Medienwerte bleiben ausgeschlossen.', 'wp-agent-companion' ),
		'category' => 'wp-agent', 'input_schema' => wpagent_pods_free_get_input_schema(), 'output_schema' => wpagent_pods_free_pod_output_schema(),
		'execute_callback' => 'wpagent_exec_get_pods_object_extension', 'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed> */
function wpagent_pods_free_paged_schema( string $key, array $item_schema ): array {
	$properties = array(
		$key => array( 'type' => 'array', 'maxItems' => WPAGENT_PODS_FREE_MAX_PER_PAGE, 'items' => $item_schema ),
		'total' => array( 'type' => 'integer' ), 'page' => array( 'type' => 'integer' ),
		'per_page' => array( 'type' => 'integer' ), 'total_pages' => array( 'type' => 'integer' ),
	);
	return array( 'type' => 'object', 'properties' => $properties, 'required' => array_keys( $properties ), 'additionalProperties' => false );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_pods_free_list_pods( $input, string $surface ) {
	$available = wpagent_pods_free_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$search = wpagent_pods_free_search( $input['search'] ?? null );
	$pagination = wpagent_pods_free_page_input( $input );
	if ( is_wp_error( $search ) || is_wp_error( $pagination ) ) {
		return is_wp_error( $search ) ? $search : $pagination;
	}
	$pods = wpagent_pods_free_load_pods();
	if ( is_wp_error( $pods ) ) {
		return $pods;
	}
	$matcher = 'settings' === $surface ? 'wpagent_pods_free_is_settings' : 'wpagent_pods_free_is_object_extension';
	$pods = array_values( array_filter( $pods, static fn( object $pod ): bool => $matcher( $pod ) && wpagent_pods_free_matches_search( $pod, $search ) ) );
	usort( $pods, static function ( object $left, object $right ): int {
		$left_args = $left->get_args();
		$right_args = $right->get_args();
		return strcasecmp( (string) ( $left_args['label'] ?? '' ), (string) ( $right_args['label'] ?? '' ) ) ?: strcmp( (string) ( $left_args['name'] ?? '' ), (string) ( $right_args['name'] ?? '' ) );
	} );
	$total = count( $pods );
	$states = array();
	foreach ( array_slice( $pods, ( $pagination['page'] - 1 ) * $pagination['per_page'], $pagination['per_page'] ) as $pod ) {
		$state = wpagent_pods_free_pod_state( $pod, 0 );
		if ( is_wp_error( $state ) ) {
			return $state;
		}
		$states[] = $state;
	}
	return array(
		'settings' === $surface ? 'settings' : 'extensions' => $states,
		'total' => $total, 'page' => $pagination['page'], 'per_page' => $pagination['per_page'],
		'total_pages' => 0 === $total ? 0 : (int) ceil( $total / $pagination['per_page'] ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_pods_settings( $input ) {
	return wpagent_pods_free_list_pods( $input, 'settings' );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_pods_settings( $input ) {
	$available = wpagent_pods_free_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$name = wpagent_pods_free_name( $input['name'] ?? null );
	$max_fields = wpagent_pods_free_max_fields( $input );
	if ( is_wp_error( $name ) || is_wp_error( $max_fields ) ) {
		return is_wp_error( $name ) ? $name : $max_fields;
	}
	$pod = wpagent_pods_free_get_pod( $name );
	if ( is_wp_error( $pod ) ) {
		return $pod;
	}
	if ( ! wpagent_pods_free_is_settings( $pod ) ) {
		return new WP_Error( 'wpagent_pods_free_not_settings', __( 'Diese Pods-Definition ist kein Settings-Pod mit Optionsspeicher.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	return wpagent_pods_free_pod_state( $pod, $max_fields );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_pods_field_groups( $input ) {
	$available = wpagent_pods_free_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$search = wpagent_pods_free_search( $input['search'] ?? null );
	$pagination = wpagent_pods_free_page_input( $input );
	if ( is_wp_error( $search ) || is_wp_error( $pagination ) ) {
		return is_wp_error( $search ) ? $search : $pagination;
	}
	$pod = null;
	if ( array_key_exists( 'pod_name', $input ) ) {
		$name = wpagent_pods_free_name( $input['pod_name'], 'pod_name' );
		if ( is_wp_error( $name ) ) {
			return $name;
		}
		$pod = wpagent_pods_free_get_pod( $name );
		if ( is_wp_error( $pod ) ) {
			return $pod;
		}
	}
	$groups = wpagent_pods_free_load_groups( $pod );
	if ( is_wp_error( $groups ) ) {
		return $groups;
	}
	$groups = array_values( array_filter( $groups, static fn( object $group ): bool => wpagent_pods_free_group_matches_search( $group, $search ) ) );
	usort( $groups, static function ( object $left, object $right ): int {
		$left_args = $left->get_args();
		$right_args = $right->get_args();
		$weight = (int) ( $left_args['weight'] ?? 0 ) <=> (int) ( $right_args['weight'] ?? 0 );
		return 0 !== $weight ? $weight : strcasecmp( (string) ( $left_args['label'] ?? '' ), (string) ( $right_args['label'] ?? '' ) );
	} );
	$total = count( $groups );
	$states = array();
	foreach ( array_slice( $groups, ( $pagination['page'] - 1 ) * $pagination['per_page'], $pagination['per_page'] ) as $group ) {
		$group_args = $group->get_args();
		$parent = $pod;
		if ( null === $parent ) {
			$parent = wpagent_pods_free_get_pod_by_id( (int) ( $group_args['parent'] ?? 0 ) );
			if ( is_wp_error( $parent ) ) {
				return new WP_Error( 'wpagent_pods_free_group_parent_missing', __( 'Die Eltern-Definition einer Pods-Feldgruppe konnte nicht sicher gelesen werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
			}
		}
		$state = wpagent_pods_free_group_state( $parent, $group, 0 );
		if ( is_wp_error( $state ) ) {
			return $state;
		}
		$states[] = $state;
	}
	return array(
		'groups' => $states, 'total' => $total, 'page' => $pagination['page'], 'per_page' => $pagination['per_page'],
		'total_pages' => 0 === $total ? 0 : (int) ceil( $total / $pagination['per_page'] ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_pods_field_group( $input ) {
	$available = wpagent_pods_free_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$pod_name = wpagent_pods_free_name( $input['pod_name'] ?? null, 'pod_name' );
	$name = wpagent_pods_free_name( $input['name'] ?? null );
	$max_fields = wpagent_pods_free_max_fields( $input );
	foreach ( array( $pod_name, $name, $max_fields ) as $value ) {
		if ( is_wp_error( $value ) ) {
			return $value;
		}
	}
	$pod = wpagent_pods_free_get_pod( $pod_name );
	if ( is_wp_error( $pod ) ) {
		return $pod;
	}
	$group = wpagent_pods_free_get_group( $pod, $name );
	return is_wp_error( $group ) ? $group : wpagent_pods_free_group_state( $pod, $group, $max_fields );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_pods_object_extensions( $input ) {
	return wpagent_pods_free_list_pods( $input, 'extensions' );
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_pods_object_extension( $input ) {
	$available = wpagent_pods_free_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$name = wpagent_pods_free_name( $input['name'] ?? null );
	$max_fields = wpagent_pods_free_max_fields( $input );
	if ( is_wp_error( $name ) || is_wp_error( $max_fields ) ) {
		return is_wp_error( $name ) ? $name : $max_fields;
	}
	$pod = wpagent_pods_free_get_pod( $name );
	if ( is_wp_error( $pod ) ) {
		return $pod;
	}
	if ( ! wpagent_pods_free_is_object_extension( $pod ) ) {
		return new WP_Error( 'wpagent_pods_free_not_extension', __( 'Diese Pods-Definition ist keine Erweiterung eines integrierten WordPress-Objekts.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	return wpagent_pods_free_pod_state( $pod, $max_fields );
}
