<?php
/**
 * Ability: wp-agent/render-check
 *
 * Read-only. Parses the post content, counts blocks, flags core/freeform (the
 * silent classic-editor fallback signal) and renders the server HTML so the
 * pipeline can verify the post actually became blocks.
 *
 * @package WPAgentCompanion
 */

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

function wpagent_ability_render_check(): array {
	return array(
		'label'               => __( 'Render-Check', 'wp-agent-companion' ),
		'description'         => __( 'Parst den Beitragsinhalt, zählt Blöcke, flaggt core/freeform und rendert das Server-HTML zur Kontrolle.', '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(
				'post_id'              => array( 'type' => 'integer' ),
				'block_count'          => array( 'type' => 'integer' ),
				'freeform_count'       => array( 'type' => 'integer' ),
				'has_freeform'         => array( 'type' => 'boolean' ),
				'block_types'          => array(
					'type'  => 'array',
					'items' => array( 'type' => 'string' ),
				),
				'rendered_html_length' => array( 'type' => 'integer' ),
				'word_count'           => array( 'type' => 'integer' ),
			),
		),
		'execute_callback'    => 'wpagent_exec_render_check',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => true,
				'destructive' => false,
				'idempotent'  => true,
			),
		),
	);
}

/**
 * @param mixed $input
 * @return array|WP_Error
 */
function wpagent_exec_render_check( $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 ) );
	}
	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 );
	$html   = do_blocks( $post->post_content );
	$text   = trim( wp_strip_all_tags( $html ) );
	$words  = ( '' === $text ) ? 0 : count( preg_split( '/\s+/', $text ) );

	return array(
		'post_id'              => $post_id,
		'block_count'          => $report['block_count'],
		'freeform_count'       => $report['freeform_count'],
		'has_freeform'         => $report['freeform_count'] > 0,
		'block_types'          => $report['block_types'],
		'rendered_html_length' => strlen( $html ),
		'word_count'           => $words,
	);
}
