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

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

function wpagent_ability_get_oceanwp_post_design(): array {
	return array(
		'label'               => __( 'OceanWP-Beitragsdesign lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest individuelle OceanWP-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_oceanwp_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_oceanwp_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_oceanwp_post_design( $input ) {
	if ( ! wpagent_oceanwp_is_active() ) {
		return new WP_Error( 'wpagent_oceanwp_inactive', __( 'OceanWP oder ein OceanWP-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_oceanwp_runtime_ready() ) {
		return new WP_Error( 'wpagent_oceanwp_runtime_missing', __( 'Die aktive OceanWP-Version stellt den geprüften Beitragslayout-Weg nicht bereit. Unterstützt wird OceanWP ab Version 4.1.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$post = wpagent_oceanwp_post_target( absint( is_array( $input ) ? ( $input['post_id'] ?? 0 ) : 0 ) );
	if ( is_wp_error( $post ) ) {
		return $post;
	}
	$snapshot = wpagent_oceanwp_post_snapshot( $post );
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	return array(
		'post_id'    => (int) $post->ID,
		'post_type'  => $post->post_type,
		'overrides'  => wpagent_oceanwp_post_normalize( $snapshot ),
		'state_hash' => wpagent_oceanwp_post_state_hash( $snapshot ),
	);
}
