<?php
/** Read eligible OceanWP library templates and per-post assignments. */

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

function wpagent_ability_list_oceanwp_library_templates(): array {
	$template_schema = array(
		'type'                 => 'object',
		'properties'           => array(
			'id'           => array( 'type' => 'integer' ),
			'title'        => array( 'type' => 'string' ),
			'content_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			'block_types'  => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
		),
		'required'             => array( 'id', 'title', 'content_hash', 'block_types' ),
		'additionalProperties' => false,
	);
	return array(
		'label'               => __( 'OceanWP-Library-Templates auflisten', 'wp-agent-companion' ),
		'description'         => __( 'Listet ausschließlich veröffentlichte, statische und shortcodefreie Core-Block-Templates aus OceanWP My Library auf.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'page'     => array( 'type' => 'integer', 'minimum' => 1 ),
				'per_page' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => WPAGENT_OCEAN_EXTRA_LIBRARY_MAX_TEMPLATES ),
				'search'   => array( 'type' => 'string', 'maxLength' => 200 ),
			),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'templates'      => array( 'type' => 'array', 'items' => $template_schema ),
				'total'          => array( 'type' => 'integer' ),
				'page'           => array( 'type' => 'integer' ),
				'per_page'       => array( 'type' => 'integer' ),
				'excluded_unsafe' => array( 'type' => 'integer' ),
			),
			'required'             => array( 'templates', 'total', 'page', 'per_page', 'excluded_unsafe' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_list_oceanwp_library_templates',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_list_oceanwp_library_templates( $input ) {
	$ready = wpagent_ocean_extra_library_require_runtime();
	if ( is_wp_error( $ready ) ) {
		return $ready;
	}
	$input    = is_array( $input ) ? $input : array();
	$page     = max( 1, absint( $input['page'] ?? 1 ) );
	$per_page = min( WPAGENT_OCEAN_EXTRA_LIBRARY_MAX_TEMPLATES, max( 1, absint( $input['per_page'] ?? 20 ) ) );
	$search   = is_string( $input['search'] ?? null ) ? sanitize_text_field( $input['search'] ) : '';
	$query    = new WP_Query(
		array(
			'post_type'              => 'oceanwp_library',
			'post_status'            => 'publish',
			'posts_per_page'         => $per_page,
			'paged'                  => $page,
			's'                      => $search,
			'orderby'                => array( 'title' => 'ASC', 'ID' => 'ASC' ),
			'update_post_meta_cache' => true,
			'update_post_term_cache' => false,
		)
	);
	$templates = array();
	$excluded  = 0;
	foreach ( $query->posts as $post ) {
		$descriptor = wpagent_ocean_extra_library_template( (int) $post->ID );
		if ( is_wp_error( $descriptor ) ) {
			++$excluded;
			continue;
		}
		$templates[] = $descriptor;
	}
	return array( 'templates' => $templates, 'total' => (int) $query->found_posts, 'page' => $page, 'per_page' => $per_page, 'excluded_unsafe' => $excluded );
}

function wpagent_ability_get_oceanwp_post_library_templates(): array {
	return array(
		'label'               => __( 'OceanWP-Library-Zuordnung lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest die sicheren OceanWP-Library-Zuordnungen für Header und Footer eines Beitrags samt Konflikthash.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1 ) ), 'required' => array( 'post_id' ), 'additionalProperties' => false ),
		'output_schema'       => wpagent_ocean_extra_library_state_schema(),
		'execute_callback'    => 'wpagent_exec_get_oceanwp_post_library_templates',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_oceanwp_post_library_templates( $input ) {
	$ready = wpagent_ocean_extra_library_require_runtime();
	if ( is_wp_error( $ready ) ) {
		return $ready;
	}
	$target = wpagent_oceanwp_extra_layout_post_target( absint( is_array( $input ) ? ( $input['post_id'] ?? 0 ) : 0 ) );
	if ( is_wp_error( $target ) ) {
		return $target;
	}
	$snapshot = wpagent_ocean_extra_library_snapshot( $target['post'], $target['blog_id'] );
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	$state = wpagent_ocean_extra_library_normalize( $snapshot );
	return array( 'post_id' => $target['post']->ID, 'post_type' => $target['post']->post_type, 'header' => $state['header'], 'footer' => $state['footer'], 'state_hash' => wpagent_ocean_extra_library_state_hash( $snapshot ) );
}
