<?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', 'minimum' => 1, 'maximum' => 2147483647 ),
			),
			'required'   => array( 'post_id' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'       => 'object',
			'additionalProperties' => false,
			'properties' => array(
				'post_id'              => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 2147483647 ),
				'block_count'          => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => WPAGENT_BUILDER_READ_MAX_BLOCKS ),
				'freeform_count'       => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => WPAGENT_BUILDER_READ_MAX_BLOCKS ),
				'has_freeform'         => array( 'type' => 'boolean' ),
				'block_types'          => array(
					'type'  => 'array',
					'maxItems' => 128,
					'items' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 128, 'pattern' => '^[A-Za-z0-9][A-Za-z0-9._:/-]*$' ),
				),
				'rendered_html_length' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => WPAGENT_BUILDER_READ_MAX_RENDERED_HTML_BYTES ),
				'word_count'           => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 250000 ),
			),
			'required'   => array( 'post_id', 'block_count', 'freeform_count', 'has_freeform', 'block_types', 'rendered_html_length', 'word_count' ),
		),
		'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 ) {
	$post_id = wpagent_builder_read_post_id_from_input( $input );
	if ( is_wp_error( $post_id ) ) {
		return $post_id;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$post = get_post( $post_id );
	if ( ! $post ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$content_valid = wpagent_builder_read_validate_post_content( $post->post_content );
	if ( is_wp_error( $content_valid ) ) {
		return $content_valid;
	}

	$report = wpagent_block_report( $post->post_content );
	$report_valid = wpagent_builder_read_validate_block_report( $report );
	if ( is_wp_error( $report_valid ) ) {
		return $report_valid;
	}
	$html   = do_blocks( $post->post_content );
	if ( strlen( $html ) > WPAGENT_BUILDER_READ_MAX_RENDERED_HTML_BYTES ) {
		return new WP_Error( 'wpagent_builder_read_too_large', __( 'Die gerenderte Builder-Ausgabe überschreitet die sichere Lesegrenze.', 'wp-agent-companion' ), array( 'status' => 413 ) );
	}
	$text   = trim( wp_strip_all_tags( $html ) );
	$words  = ( '' === $text ) ? 0 : count( preg_split( '/\s+/', $text ) );

	$result = 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,
	);
	$output_valid = wpagent_builder_read_validate_render_report( $result );
	return is_wp_error( $output_valid ) ? $output_valid : $result;
}
