<?php
/** Read verified per-post GeneratePress layout overrides. */

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

function wpagent_ability_get_generatepress_post_design(): array {
	return array(
		'label'               => __( 'GeneratePress-Beitragsdesign lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest individuelle GeneratePress-Layoutvorgaben 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_generatepress_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_generatepress_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_generatepress_post_design( $input ) {
	if ( ! wpagent_generatepress_is_active() ) {
		return new WP_Error( 'wpagent_generatepress_inactive', __( 'GeneratePress oder ein GeneratePress-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_generatepress_runtime_ready() ) {
		return new WP_Error( 'wpagent_generatepress_runtime_missing', __( 'Die aktive GeneratePress-Version stellt den geprüften Beitragslayout-Weg nicht bereit. Unterstützt wird GeneratePress ab Version 3.6.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$post = wpagent_generatepress_post_target( absint( is_array( $input ) ? ( $input['post_id'] ?? 0 ) : 0 ) );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	$snapshot = wpagent_generatepress_post_snapshot( $post );
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	$overrides = wpagent_generatepress_post_normalize( $snapshot );
	if ( is_wp_error( $overrides ) ) {
		return $overrides;
	}
	return array(
		'post_id'    => (int) $post->ID,
		'post_type'  => $post->post_type,
		'overrides'  => $overrides,
		'state_hash' => wpagent_generatepress_post_state_hash( $snapshot ),
	);
}
