<?php
/** Read verified per-post Astra design overrides. */

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

function wpagent_ability_get_astra_post_design(): array {
	return array(
		'label'               => __( 'Astra-Beitragsdesign lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest sichere individuelle Astra-Layout- und Sichtbarkeitsvorgaben 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'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'post_id'    => array( 'type' => 'integer' ),
				'post_type'  => array( 'type' => 'string' ),
				'overrides'  => wpagent_astra_post_override_schema( true ),
				'state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required'             => array( 'post_id', 'post_type', 'overrides', 'state_hash' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_get_astra_post_design',
		'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_astra_post_design( $input ) {
	if ( ! wpagent_astra_is_active() ) {
		return new WP_Error( 'wpagent_astra_inactive', __( 'Astra oder ein Astra-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_astra_read_abilities_enabled() ) {
		return new WP_Error( 'wpagent_astra_abilities_disabled', __( 'Aktiviere zuerst die Abilities in den Astra-Einstellungen.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$post = wpagent_astra_post_target( absint( is_array( $input ) ? ( $input['post_id'] ?? 0 ) : 0 ) );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	$snapshot = wpagent_astra_post_snapshot( $post );
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	return array(
		'post_id'    => (int) $post->ID,
		'post_type'  => $post->post_type,
		'overrides'  => wpagent_astra_post_normalize( $snapshot ),
		'state_hash' => wpagent_astra_post_state_hash( $snapshot ),
	);
}
