<?php
/** Verified read and write abilities for GeneratePress design settings. */

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

function wpagent_ability_get_generatepress_design(): array {
	return array(
		'label'               => __( 'GeneratePress-Design lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest fünf begrenzte GeneratePress-Designbereiche und einen Konflikt-Hash.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'properties' => array(), 'additionalProperties' => false, 'default' => array() ),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'active'     => array( 'type' => 'boolean' ),
				'version'    => array( 'type' => 'string' ),
				'sections'   => array( 'type' => 'object', 'additionalProperties' => true ),
				'state_hash' => array( 'type' => array( 'string', 'null' ), 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required'             => array( 'active', 'version', 'sections', 'state_hash' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_get_generatepress_design',
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true ),
			'mcp'          => array(
				'uri'         => 'wpagently://integrations/generatepress',
				'annotations' => array( 'audience' => array( 'assistant' ) ),
			),
		),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_generatepress_design( $input = array() ) {
	$version = wpagent_generatepress_version();
	if ( ! wpagent_generatepress_is_active() ) {
		return array( 'active' => false, 'version' => $version, 'sections' => new stdClass(), 'state_hash' => null );
	}
	if ( ! wpagent_generatepress_runtime_ready() ) {
		return new WP_Error( 'wpagent_generatepress_runtime_missing', __( 'Die aktive GeneratePress-Version stellt den geprüften Einstellungs- und CSS-Pfad nicht bereit.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$snapshot = wpagent_generatepress_snapshot();
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	$sections = array();
	foreach ( array_keys( wpagent_generatepress_section_schemas() ) as $section ) {
		$current = wpagent_generatepress_read_section( $section, $snapshot['settings']['value'] );
		if ( is_wp_error( $current ) ) {
			return $current;
		}
		$sections[ str_replace( '-', '_', $section ) ] = $current;
	}
	return array(
		'active'     => true,
		'version'    => $version,
		'sections'   => $sections,
		'state_hash' => wpagent_generatepress_state_hash( $snapshot ),
	);
}

function wpagent_ability_update_generatepress_design(): array {
	return array(
		'label'               => __( 'GeneratePress-Design aktualisieren', 'wp-agent-companion' ),
		'description'         => __( 'Ändert einen begrenzten GeneratePress-Designbereich mit Konfliktschutz, Sperre, CSS-Neuaufbau, Readback und Rollback.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'expected_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'section'       => array( 'type' => 'string', 'enum' => array_keys( wpagent_generatepress_section_schemas() ) ),
				'settings'      => array( 'type' => 'object', 'maxProperties' => 20, 'additionalProperties' => true ),
			),
			'required'             => array( 'expected_hash', 'section', 'settings' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'section'       => array( 'type' => 'string', 'enum' => array_keys( wpagent_generatepress_section_schemas() ) ),
				'current'       => array( 'type' => array( 'object', 'array' ) ),
				'previous_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'state_hash'    => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'verified'      => array( 'type' => 'boolean' ),
			),
			'required'             => array( 'section', 'current', 'previous_hash', 'state_hash', 'verified' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_update_generatepress_design',
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => true ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_generatepress_design( $input ) {
	if ( ! wpagent_generatepress_is_active() ) {
		return new WP_Error( 'wpagent_generatepress_inactive', __( 'GeneratePress oder ein GeneratePress-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_generatepress_runtime_ready() ) {
		return new WP_Error( 'wpagent_generatepress_runtime_missing', __( 'Die aktive GeneratePress-Version stellt den geprüften Einstellungs- und CSS-Pfad nicht bereit.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$section = is_array( $input ) ? (string) ( $input['section'] ?? '' ) : '';
	$lock    = wpagent_generatepress_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$previous = wpagent_generatepress_snapshot();
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		$previous_hash = wpagent_generatepress_state_hash( $previous );
		$expected_hash = strtolower( (string) ( $input['expected_hash'] ?? '' ) );
		if ( ! preg_match( '/^[a-f0-9]{64}$/', $expected_hash ) || ! hash_equals( $previous_hash, $expected_hash ) ) {
			return new WP_Error( 'wpagent_generatepress_conflict', __( 'Die GeneratePress-Einstellungen haben sich seit dem Lesen geändert. Lies sie neu und wiederhole den Vorgang.', 'wp-agent-companion' ), array( 'status' => 409, 'current_hash' => $previous_hash ) );
		}
		$settings = wpagent_generatepress_validate_settings( $section, $input['settings'] ?? null, $previous['settings']['value'] );
		if ( is_wp_error( $settings ) ) {
			return $settings;
		}
		$next = wpagent_generatepress_apply_settings( $section, $previous['settings']['value'], $settings );
		if ( is_wp_error( $next ) ) {
			return $next;
		}
		$expected_current = wpagent_generatepress_read_section( $section, $next );
		if ( is_wp_error( $expected_current ) ) {
			return $expected_current;
		}
		$written = wpagent_generatepress_write_and_refresh( $next );
		if ( is_wp_error( $written ) ) {
			return wpagent_generatepress_fail_after_rollback( $previous, $previous_hash );
		}
		$fresh = wpagent_generatepress_snapshot();
		if ( is_wp_error( $fresh ) ) {
			return wpagent_generatepress_fail_after_rollback( $previous, $previous_hash );
		}
		$current = wpagent_generatepress_read_section( $section, $fresh['settings']['value'] );
		if ( is_wp_error( $current ) || maybe_serialize( $expected_current ) !== maybe_serialize( $current ) ) {
			return wpagent_generatepress_fail_after_rollback( $previous, $previous_hash );
		}
		return array(
			'section'       => $section,
			'current'       => $current,
			'previous_hash' => $previous_hash,
			'state_hash'    => wpagent_generatepress_state_hash( $fresh ),
			'verified'      => true,
		);
	} finally {
		wpagent_generatepress_release_lock( $lock );
	}
}
