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

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

/** @param array<string,mixed> $schema @return array<string,mixed> */
function wpagent_oceanwp_bound_schema( array $schema ): array {
	if ( isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) {
		foreach ( $schema['properties'] as $key => $child ) {
			if ( is_array( $child ) ) {
				$schema['properties'][ $key ] = wpagent_oceanwp_bound_schema( $child );
			}
		}
	}
	if ( isset( $schema['items'] ) && is_array( $schema['items'] ) ) {
		$schema['items'] = wpagent_oceanwp_bound_schema( $schema['items'] );
	}
	foreach ( array( 'anyOf', 'oneOf', 'allOf' ) as $keyword ) {
		if ( isset( $schema[ $keyword ] ) && is_array( $schema[ $keyword ] ) ) {
			foreach ( $schema[ $keyword ] as $key => $child ) {
				if ( is_array( $child ) ) {
					$schema[ $keyword ][ $key ] = wpagent_oceanwp_bound_schema( $child );
				}
			}
		}
	}
	$types = (array) ( $schema['type'] ?? array() );
	if ( in_array( 'object', $types, true ) && isset( $schema['properties'] ) && is_array( $schema['properties'] ) ) {
		$schema['maxProperties']        = count( $schema['properties'] );
		$schema['additionalProperties'] = false;
	}
	if ( in_array( 'array', $types, true ) && ! isset( $schema['maxItems'] ) ) {
		$schema['maxItems'] = 64;
	}
	return $schema;
}

/** @param array<string,mixed> $schema @return array<string,mixed> */
function wpagent_oceanwp_complete_object_schema( array $schema ): array {
	$schema                  = wpagent_oceanwp_bound_schema( $schema );
	$schema['required']      = array_keys( $schema['properties'] ?? array() );
	$schema['minProperties'] = count( $schema['required'] );
	return $schema;
}

/** @return array<string,array<string,mixed>> */
function wpagent_oceanwp_read_section_schemas(): array {
	$layout  = wpagent_oceanwp_complete_object_schema( wpagent_oceanwp_layout_schema() );
	$colors  = wpagent_oceanwp_bound_schema( wpagent_oceanwp_colors_schema() );
	foreach ( $colors['properties'] as $key => $color ) {
		$color['minLength']               = 0;
		$colors['properties'][ $key ] = $color;
	}
	$colors = wpagent_oceanwp_complete_object_schema( $colors );
	$buttons = wpagent_oceanwp_complete_object_schema( wpagent_oceanwp_buttons_schema() );
	$header  = wpagent_oceanwp_complete_object_schema( wpagent_oceanwp_header_schema() );
	$header['properties']['style']['enum'][] = 'custom';
	$typography = wpagent_oceanwp_bound_schema( wpagent_oceanwp_typography_schema() );
	$typography['required']      = array( 'target' );
	$typography['minProperties'] = 1;
	return array(
		'layout'     => $layout,
		'colors'     => $colors,
		'typography' => array( 'type' => 'array', 'minItems' => 2, 'maxItems' => 2, 'items' => $typography ),
		'buttons'    => $buttons,
		'header'     => $header,
	);
}

/** @return array<string,mixed> */
function wpagent_oceanwp_update_settings_schema(): array {
	$schemas = array();
	foreach ( wpagent_oceanwp_section_schemas() as $schema ) {
		$schemas[] = wpagent_oceanwp_bound_schema( $schema );
	}
	return array( 'anyOf' => $schemas );
}

/** @return array<string,mixed> */
function wpagent_oceanwp_current_section_schema(): array {
	return array( 'anyOf' => array_values( wpagent_oceanwp_read_section_schemas() ) );
}

/** @return array<string,mixed> */
function wpagent_oceanwp_sections_schema(): array {
	$properties = wpagent_oceanwp_read_section_schemas();
	return array( 'type' => 'object', 'minProperties' => 0, 'maxProperties' => count( $properties ), 'properties' => $properties, 'additionalProperties' => false );
}

function wpagent_ability_get_oceanwp_design(): array {
	return array(
		'label'               => __( 'OceanWP-Design lesen', 'wp-agent-companion' ),
		'description'         => __( 'Liest fünf begrenzte OceanWP-Designbereiche und einen Konflikt-Hash.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array( 'type' => 'object', 'properties' => array(), 'maxProperties' => 0, 'additionalProperties' => false, 'default' => array() ),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'active'     => array( 'type' => 'boolean' ),
				'version'    => array( 'type' => 'string', 'maxLength' => 64 ),
				'sections'   => wpagent_oceanwp_sections_schema(),
				'state_hash' => array( 'type' => array( 'string', 'null' ), 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required'             => array( 'active', 'version', 'sections', 'state_hash' ),
			'maxProperties'        => 4,
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_get_oceanwp_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/oceanwp',
				'annotations' => array( 'audience' => array( 'assistant' ) ),
			),
		),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_get_oceanwp_design( $input = array() ) {
	$version = wpagent_oceanwp_version();
	if ( ! wpagent_oceanwp_is_active() ) {
		return array( 'active' => false, 'version' => $version, 'sections' => new stdClass(), 'state_hash' => null );
	}
	if ( ! wpagent_oceanwp_runtime_ready() ) {
		return new WP_Error( 'wpagent_oceanwp_runtime_missing', __( 'Die aktive OceanWP-Version stellt den geprüften Einstellungsweg nicht bereit. Unterstützt wird OceanWP ab Version 4.1.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$snapshot = wpagent_oceanwp_snapshot();
	if ( is_wp_error( $snapshot ) ) {
		return $snapshot;
	}
	$sections = array();
	foreach ( array_keys( wpagent_oceanwp_section_schemas() ) as $section ) {
		$current = wpagent_oceanwp_read_section( $section, $snapshot['mods']['value'] );
		if ( is_wp_error( $current ) ) {
			return $current;
		}
		$sections[ $section ] = $current;
	}
	return array(
		'active'     => true,
		'version'    => $version,
		'sections'   => $sections,
		'state_hash' => wpagent_oceanwp_state_hash( $snapshot ),
	);
}

function wpagent_ability_update_oceanwp_design(): array {
	return array(
		'label'               => __( 'OceanWP-Design aktualisieren', 'wp-agent-companion' ),
		'description'         => __( 'Ändert einen begrenzten OceanWP-Designbereich mit Konfliktschutz, Sperre und exaktem Read-back. Nicht verifizierbare Providerzustände erfordern eine manuelle Recovery ohne automatisches 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_oceanwp_section_schemas() ) ),
				'settings'      => wpagent_oceanwp_update_settings_schema(),
			),
			'required'             => array( 'expected_hash', 'section', 'settings' ),
			'maxProperties'        => 3,
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'section'       => array( 'type' => 'string', 'enum' => array_keys( wpagent_oceanwp_section_schemas() ) ),
				'current'       => wpagent_oceanwp_current_section_schema(),
				'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' ),
			'maxProperties'        => 5,
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_update_oceanwp_design',
		'permission_callback' => 'wpagent_perm_manage_options',
		'meta'                => array( 'show_in_rest' => true, 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false ) ),
	);
}

/** @return array<string,mixed>|WP_Error */
function wpagent_exec_update_oceanwp_design( $input ) {
	if ( ! wpagent_oceanwp_is_active() ) {
		return new WP_Error( 'wpagent_oceanwp_inactive', __( 'OceanWP oder ein OceanWP-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( ! wpagent_oceanwp_runtime_ready() ) {
		return new WP_Error( 'wpagent_oceanwp_runtime_missing', __( 'Die aktive OceanWP-Version stellt den geprüften Einstellungsweg nicht bereit. Unterstützt wird OceanWP ab Version 4.1.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	$section = is_array( $input ) ? (string) ( $input['section'] ?? '' ) : '';
	$lock    = wpagent_oceanwp_acquire_lock();
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$blog_id = (int) get_current_blog_id();
		if ( ! wpagent_perm_manage_options() ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		if ( ! wpagent_oceanwp_is_active() ) {
			return new WP_Error( 'wpagent_oceanwp_inactive', __( 'OceanWP oder ein OceanWP-Child-Theme ist nicht aktiv.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		if ( ! wpagent_oceanwp_runtime_ready() ) {
			return new WP_Error( 'wpagent_oceanwp_runtime_missing', __( 'Die aktive OceanWP-Version stellt den geprüften Einstellungsweg nicht bereit. Unterstützt wird OceanWP ab Version 4.1.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$previous = wpagent_oceanwp_snapshot();
		if ( is_wp_error( $previous ) ) {
			return $previous;
		}
		$previous_hash = wpagent_oceanwp_state_hash( $previous );
		$raw_previous = wpagent_companion_read_option_row_direct( $previous['option_name'] );
		if ( ( $previous['mods']['exists'] && ( ! is_array( $raw_previous ) || maybe_unserialize( $raw_previous['raw'] ) !== $previous['mods']['value'] ) )
			|| ( ! $previous['mods']['exists'] && null !== $raw_previous ) ) {
			return new WP_Error( 'wpagent_oceanwp_conflict', __( 'Die rohe OceanWP-Theme-Mod-Option änderte sich während der Vorbereitung.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$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_oceanwp_conflict', __( 'Die OceanWP-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 ) );
		}
		$writable = wpagent_oceanwp_assert_writable_mode( $previous['mods']['value'] );
		if ( is_wp_error( $writable ) ) {
			return $writable;
		}
		foreach ( array_keys( wpagent_oceanwp_section_schemas() ) as $provider_section ) {
			$provider_state = wpagent_oceanwp_read_section( $provider_section, $previous['mods']['value'] );
			if ( is_wp_error( $provider_state ) ) {
				return $provider_state;
			}
		}
		$settings = wpagent_oceanwp_validate_settings( $section, $input['settings'] ?? null );
		if ( is_wp_error( $settings ) ) {
			return $settings;
		}
		$next = wpagent_oceanwp_apply_settings( $section, $previous['mods']['value'], $settings );
		if ( is_wp_error( $next ) ) {
			return $next;
		}
		$expected_current = wpagent_oceanwp_read_section( $section, $next );
		if ( is_wp_error( $expected_current ) ) {
			return $expected_current;
		}
		if ( ! wpagent_oceanwp_refresh_lock( $lock ) ) {
			return new WP_Error( 'wpagent_oceanwp_lock_lost', __( 'Die OceanWP-Änderung hat ihre exklusive Sperre verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		if ( ! wpagent_perm_manage_options() ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$written = wpagent_oceanwp_write( $previous['option_name'], $next, $lock, $raw_previous, $blog_id );
		if ( is_wp_error( $written ) ) {
			$data = $written->get_error_data();
			if ( ! is_array( $data ) || empty( $data['write_started'] ) ) {
				return $written;
			}
			return wpagent_oceanwp_recovery_required();
		}
		$fresh = wpagent_oceanwp_snapshot();
		if ( is_wp_error( $fresh ) ) {
			return wpagent_oceanwp_recovery_required();
		}
		$current = wpagent_oceanwp_read_section( $section, $fresh['mods']['value'] );
		$fresh_raw = wpagent_companion_read_option_row_direct( $previous['option_name'] );
		if ( is_wp_error( $current ) || ! is_array( $written ) || ! wpagent_oceanwp_option_rows_equal( $fresh_raw, $written ) || maybe_serialize( $expected_current ) !== maybe_serialize( $current ) ) {
			return wpagent_oceanwp_recovery_required();
		}
		if ( ! wpagent_oceanwp_refresh_lock( $lock ) ) {
			return wpagent_oceanwp_recovery_required();
		}
		if ( ! wpagent_perm_manage_options() ) {
			return wpagent_oceanwp_recovery_required();
		}
		return array(
			'section'       => $section,
			'current'       => $current,
			'previous_hash' => $previous_hash,
			'state_hash'    => wpagent_oceanwp_state_hash( $fresh ),
			'verified'      => true,
		);
	} finally {
		wpagent_oceanwp_release_lock( $lock );
	}
}
