<?php
/**
 * ppok/post/get-blocks — return parsed block tree for a post.
 *
 * Thin wrapper around parse_blocks(). Read-only. Cap: edit_post per ID.
 *
 * @package Ppok\AIToolkit
 * @license GPL-2.0-or-later
 */

namespace Ppok\AIToolkit\Abilities;

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

final class Post_Get_Blocks {

	public const SLUG = 'ppok/get-post-blocks';

	public static function descriptor(): array {
		return array(
			'label'               => __( 'Get post blocks', 'ppok-ai-toolkit' ),
			'description'         => __( 'Returns a post\'s content parsed into a WP block tree (the same shape parse_blocks() produces). Read-only.', 'ppok-ai-toolkit' ),
			'category'            => 'ppok',
			'input_schema'        => self::input_schema(),
			'output_schema'       => self::output_schema(),
			'permission_callback' => array( __CLASS__, 'permission_callback' ),
			'execute_callback'    => array( __CLASS__, 'execute_callback' ),
			'meta'                => array(
				'show_in_rest' => true,
				'mcp'          => array( 'public' => true ),
				'ppok'         => array( 'write' => false ),
			),
		);
	}

	public static function input_schema(): array {
		return array(
			'type'                 => 'object',
			'required'             => array( 'post_id' ),
			'additionalProperties' => false,
			'properties'           => array(
				'post_id' => array(
					'type'    => 'integer',
					'minimum' => 1,
				),
			),
		);
	}

	public static function output_schema(): array {
		return array(
			'type'       => 'object',
			'required'   => array( 'post_id', 'post_status', 'post_type', 'blocks' ),
			'properties' => array(
				'post_id'     => array( 'type' => 'integer' ),
				'post_status' => array( 'type' => 'string' ),
				'post_type'   => array( 'type' => 'string' ),
				'blocks'      => array( 'type' => 'array' ),
			),
		);
	}

	public static function example(): array {
		return array(
			'post_id' => 1,
		);
	}

	public static function permission_callback( array $args = array() ): bool {
		$post_id = isset( $args['post_id'] ) ? (int) $args['post_id'] : 0;
		if ( $post_id < 1 ) {
			return false;
		}
		return current_user_can( 'edit_post', $post_id );
	}

	public static function execute_callback( array $args = array() ) {
		$post_id = isset( $args['post_id'] ) ? (int) $args['post_id'] : 0;
		$post    = $post_id > 0 ? get_post( $post_id ) : null;

		if ( ! $post instanceof \WP_Post ) {
			return new \WP_Error(
				'ppok_post_not_found',
				__( 'Post not found.', 'ppok-ai-toolkit' ),
				array( 'status' => 404 )
			);
		}

		return array(
			'post_id'     => (int) $post->ID,
			'post_status' => (string) $post->post_status,
			'post_type'   => (string) $post->post_type,
			'blocks'      => parse_blocks( (string) $post->post_content ),
		);
	}
}
