<?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' ) ),
			'required' => array( 'post_id' ),
		),
		'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' ),
			'built_with_elementor' => array( 'type' => 'boolean' ),
			'elements' => array( 'type' => 'array', 'items' => array( 'type' => 'object', 'additionalProperties' => true ) ),
			'settings' => array( 'type' => 'object', 'additionalProperties' => true ),
			'element_count' => array( 'type' => 'integer' ),
			'widget_types' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ) ),
			'elementor_version' => array( 'type' => 'string' ),
			'edit_url' => array( 'type' => 'string' ),
			'hash' => array( 'type' => 'string' ),
		),
	);
}

/** @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;
	}
	return wpagent_elementor_document_state( $loaded['post']->ID, $loaded['document'] );
}
