<?php
/**
 * Ability: wp-agent/get-post
 *
 * Read-only. Liest die Kern-Metadaten eines Beitrags oder einer Seite (jeder
 * registrierte, öffentliche Post-Type) plus einen Block-Report, damit der
 * Aufrufer ohne einen zweiten render-check-Aufruf weiß, ob der Inhalt bereits
 * aus Blocks besteht.
 *
 * @package WPAgentCompanion
 */

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

function wpagent_ability_get_post(): array {
	return array(
		'label'               => __( 'Beitrag lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest Kern-Metadaten eines Beitrags oder einer Seite inklusive Block-Report und exaktem state_hash für einen konfliktgeschützten Folge-Write.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'       => 'object',
			'properties' => array(
				'post_id' => array( 'type' => 'integer' ),
			),
			'required'   => array( 'post_id' ),
		),
		'output_schema'       => array(
			'type'       => 'object',
			'properties' => array(
				'id'             => array( 'type' => 'integer' ),
				'post_type'      => array( 'type' => 'string' ),
				'status'         => array( 'type' => 'string' ),
				'title'          => array( 'type' => 'string' ),
				'slug'           => array( 'type' => 'string' ),
				'excerpt'        => array( 'type' => 'string' ),
				'date'           => array( 'type' => 'string' ),
				'modified'       => array( 'type' => 'string' ),
				'parent'         => array( 'type' => 'integer' ),
				'menu_order'     => array( 'type' => 'integer' ),
				'block_count'    => array( 'type' => 'integer' ),
				'freeform_count' => array( 'type' => 'integer' ),
				'state_hash'     => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_get_post',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => true,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * Hashes the exact core-post state guarded by wp-agent/update-post.
 *
 * Modified timestamps are deliberately excluded. WordPress stores them with
 * second precision, while the actual values below detect same-second writes.
 */
function wpagent_post_state_hash( WP_Post $post ): string {
	$state = array(
		'ID'             => (int) $post->ID,
		'post_type'      => (string) $post->post_type,
		'post_author'    => (int) $post->post_author,
		'post_title'     => (string) $post->post_title,
		'post_content'   => (string) $post->post_content,
		'post_excerpt'   => (string) $post->post_excerpt,
		'post_name'      => (string) $post->post_name,
		'post_status'    => (string) $post->post_status,
		'post_date'      => (string) $post->post_date,
		'post_date_gmt'  => (string) $post->post_date_gmt,
		'post_parent'    => (int) $post->post_parent,
		'menu_order'     => (int) $post->menu_order,
		'post_password'  => (string) $post->post_password,
		'comment_status' => (string) $post->comment_status,
		'ping_status'    => (string) $post->ping_status,
	);
	return hash( 'sha256', "wpagently-post-state-v1\0" . serialize( $state ) );
}

/**
 * @param mixed $input
 * @return array|WP_Error
 */
function wpagent_exec_get_post( $input ) {
	$input   = is_array( $input ) ? $input : array();
	$post_id = (int) ( $input['post_id'] ?? 0 );
	$post    = get_post( $post_id );

	if ( ! $post ) {
		return new WP_Error( 'wpagent_no_post', __( 'Beitrag nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	// current_user_can( 'edit_post', ... ) löst über WordPress' eigene
	// Meta-Capability-Zuordnung automatisch die richtige Capability für den
	// jeweiligen Post-Type auf (z. B. edit_pages für eine Seite), unabhängig
	// von der groben permission_callback-Schranke oben.
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}

	$report = wpagent_block_report( $post->post_content );

	return array(
		'id'             => $post_id,
		'post_type'      => $post->post_type,
		'status'         => $post->post_status,
		'title'          => $post->post_title,
		'slug'           => $post->post_name,
		'excerpt'        => $post->post_excerpt,
		'date'           => $post->post_date,
		'modified'       => $post->post_modified,
		'parent'         => (int) $post->post_parent,
		'menu_order'     => (int) $post->menu_order,
		'block_count'    => $report['block_count'],
		'freeform_count' => $report['freeform_count'],
		'state_hash'     => wpagent_post_state_hash( $post ),
	);
}
