<?php
/** Read-only native Elementor document ability. */

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

function wpagent_ability_get_elementor_document(): array {
	return array(
		'label' => __( 'Elementor-Dokument lesen', 'wp-agent-companion' ),
		'description' => __( 'Liest die von Elementor selbst normalisierte Elementstruktur und Seiteneinstellungen mit Konflikt-Hash.', '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_elementor_document_output_schema(),
		'execute_callback' => 'wpagent_exec_get_elementor_document',
		'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_elementor_document_output_schema(): array {
	return array(
		'type'                 => 'object',
		'properties'           => array(
			'post_id'             => array( 'type' => 'integer', 'minimum' => 1 ),
			'built_with_elementor' => array( 'type' => 'boolean' ),
			'elements'            => wpagent_elementor_json_document_schema(),
			'settings'            => wpagent_elementor_json_document_schema(),
			'element_count'       => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => WPAGENT_ELEMENTOR_MAX_ELEMENTS ),
			'widget_types'        => array( 'type' => 'array', 'maxItems' => WPAGENT_ELEMENTOR_MAX_ELEMENTS, 'items' => array( 'type' => 'string', 'maxLength' => 128 ) ),
			'elementor_version'   => array( 'type' => 'string', 'maxLength' => 64 ),
			'edit_url'            => array( 'type' => 'string', 'maxLength' => 2048 ),
			'hash'                => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
		),
		'required'             => array( 'post_id', 'built_with_elementor', 'elements', 'settings', 'element_count', 'widget_types', 'elementor_version', 'edit_url', 'hash' ),
		'additionalProperties' => false,
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_elementor_document( $input ) {
	$input = is_array( $input ) ? $input : array();
	$loaded = wpagent_elementor_editable_document( absint( $input['post_id'] ?? 0 ) );
	if ( is_wp_error( $loaded ) ) {
		return $loaded;
	}
	$state = wpagent_elementor_document_state( $loaded['post']->ID, $loaded['document'] );
	return wpagent_elementor_publicize_result( $state );
}
