<?php
/** Read-only abilities for native Pods content models and fields. */

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

function wpagent_ability_list_pods_models(): array {
	return array(
		'label'       => __( 'Pods-Modelle auflisten', 'wp-agent-companion' ),
		'description' => __( 'Listet eigenständige Pods-Inhaltstypen und Taxonomien samt Feldern, Laufzeitstatus, Inhaltszahlen, Beziehungszahlen und Konflikt-Hashes. Erweiterte WordPress-Objekte und eigene Tabellen bleiben ausgeschlossen.', 'wp-agent-companion' ),
		'category'    => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array(
				'kind' => array( 'type' => 'string', 'enum' => array( 'post_type', 'taxonomy' ) ),
				'search' => array( 'type' => 'string', 'maxLength' => 100 ),
				'page' => array( 'type' => 'integer', 'minimum' => 1, 'default' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 50, 'default' => 20 ),
			),
			'additionalProperties' => false,
		),
		'output_schema' => array(
			'type' => 'object',
			'properties' => array(
				'models' => array( 'type' => 'array', 'items' => wpagent_pods_model_output_schema() ),
				'total' => array( 'type' => 'integer' ), 'page' => array( 'type' => 'integer' ),
				'per_page' => array( 'type' => 'integer' ), 'total_pages' => array( 'type' => 'integer' ),
			),
			'required' => array( 'models', 'total', 'page', 'per_page', 'total_pages' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_list_pods_models',
		'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_model(): array {
	return array(
		'label'       => __( 'Pods-Modell lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest ein eigenständiges Pods-Modell vollständig genug für konfliktgeschützte Modell- und Feldänderungen.', 'wp-agent-companion' ),
		'category'    => 'wp-agent',
		'input_schema' => array(
			'type' => 'object',
			'properties' => array( 'name' => array( 'type' => 'string', 'pattern' => '^[a-z][a-z0-9_]{0,63}$' ) ),
			'required' => array( 'name' ), 'additionalProperties' => false,
		),
		'output_schema'       => wpagent_pods_model_output_schema(),
		'execute_callback'    => 'wpagent_exec_get_pods_model',
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta' => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_pods_models( $input ) {
	$available = wpagent_pods_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$kind  = is_string( $input['kind'] ?? null ) ? $input['kind'] : '';
	if ( '' !== $kind && ! in_array( $kind, array( 'post_type', 'taxonomy' ), true ) ) {
		return new WP_Error( 'wpagent_pods_kind', __( 'kind muss post_type oder taxonomy sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$search = is_string( $input['search'] ?? null ) ? trim( $input['search'] ) : '';
	if ( wpagent_pods_text_length( $search ) > 100 || sanitize_text_field( $search ) !== $search ) {
		return new WP_Error( 'wpagent_pods_search', __( 'search muss reiner Text mit höchstens 100 Zeichen sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$page     = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = max( 1, min( 50, absint( $input['per_page'] ?? 20 ) ) );
	try {
		$pods = pods_api()->load_pods( array( 'type' => '' === $kind ? array( 'post_type', 'taxonomy' ) : $kind, 'bypass_cache' => true ) );
	} catch ( Throwable $error ) {
		return new WP_Error( 'wpagent_pods_list_failed', __( 'Die Pods-Modelle konnten nicht aufgelistet werden.', 'wp-agent-companion' ), array( 'status' => 500 ) );
	}
	$needle = function_exists( 'mb_strtolower' ) ? mb_strtolower( $search, 'UTF-8' ) : strtolower( $search );
	$models = array();
	foreach ( is_array( $pods ) ? $pods : array() as $pod ) {
		if ( ! is_object( $pod ) || ! is_callable( array( $pod, 'get_args' ) ) ) {
			continue;
		}
		$args = $pod->get_args();
		if ( ! in_array( (string) ( $args['type'] ?? '' ), array( 'post_type', 'taxonomy' ), true ) || 'meta' !== (string) ( $args['storage'] ?? '' ) || '' !== (string) ( $args['object'] ?? '' ) ) {
			continue;
		}
		$haystack = (string) ( $args['name'] ?? '' ) . ' ' . (string) ( $args['label'] ?? '' ) . ' ' . (string) ( $args['label_singular'] ?? '' );
		$haystack = function_exists( 'mb_strtolower' ) ? mb_strtolower( $haystack, 'UTF-8' ) : strtolower( $haystack );
		if ( '' !== $needle && false === strpos( $haystack, $needle ) ) {
			continue;
		}
		$models[] = $pod;
	}
	usort( $models, static function ( object $a, object $b ): int {
		$a_args = $a->get_args();
		$b_args = $b->get_args();
		return strcasecmp( (string) ( $a_args['label'] ?? $a_args['name'] ), (string) ( $b_args['label'] ?? $b_args['name'] ) );
	} );
	$total = count( $models );
	return array(
		'models' => array_map( 'wpagent_pods_model_state', array_slice( $models, ( $page - 1 ) * $per_page, $per_page ) ),
		'total' => $total, 'page' => $page, 'per_page' => $per_page,
		'total_pages' => 0 === $total ? 0 : (int) ceil( $total / $per_page ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_pods_model( $input ) {
	$available = wpagent_pods_require_api();
	if ( is_wp_error( $available ) ) {
		return $available;
	}
	$input = is_array( $input ) ? $input : array();
	$pod   = wpagent_pods_get_model( $input['name'] ?? null );
	return is_wp_error( $pod ) ? $pod : wpagent_pods_model_state( $pod );
}
