<?php
/**
 * Ability: wp-agent/set-alt-text
 *
 * Writes the attachment alt-text meta only with a hash of the attachment's
 * Core state plus the exact underlying meta-row representation. Empty text is
 * intentional and remains valid, including the distinction between an absent
 * meta row and an explicitly stored empty string.
 *
 * @package WPAgentCompanion
 */

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

define( 'WPAGENT_ALT_TEXT_MAX_LENGTH', 1000 );

/** Measures characters when mbstring is available, otherwise safely bounds bytes. */
function wpagent_alt_text_character_length( string $value ): int {
	return function_exists( 'mb_strlen' ) ? (int) mb_strlen( $value, 'UTF-8' ) : strlen( $value );
}

function wpagent_ability_set_alt_text(): array {
	return array(
		'label'               => __( 'Alt-Text setzen', 'wp-agent-companion' ),
		'description'         => __( 'Setzt den Alt-Text eines Medienbeitrags konfliktgeschützt mit dem state_hash aus list-media, einem anhangsspezifischen Lock und exakter Meta-Rückleseprüfung. Ein leerer String ist gültig.', 'wp-agent-companion' ),
		'category'            => 'wp-agent',
		'input_schema'        => array(
			'type'                 => 'object',
			'properties'           => array(
				'attachment_id'       => array( 'type' => 'integer', 'minimum' => 1 ),
				'alt'                 => array( 'type' => 'string', 'maxLength' => WPAGENT_ALT_TEXT_MAX_LENGTH ),
				'expected_state_hash' => array(
					'type'        => 'string',
					'pattern'     => '^[a-f0-9]{64}$',
					'description' => __( 'Exakter state_hash aus list-media. Bindet Anhang und die vollständige Alt-Text-Metarepräsentation.', 'wp-agent-companion' ),
				),
			),
			'required'             => array( 'attachment_id', 'alt', 'expected_state_hash' ),
			'additionalProperties' => false,
		),
		'output_schema'       => array(
			'type'                 => 'object',
			'properties'           => array(
				'attachment_id'       => array( 'type' => 'integer', 'minimum' => 1 ),
				'alt'                 => array( 'type' => 'string', 'maxLength' => WPAGENT_ALT_TEXT_MAX_LENGTH ),
				'verified'            => array( 'type' => 'boolean' ),
				'previous_state_hash' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
				'state_hash'          => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ),
			),
			'required'             => array( 'attachment_id', 'alt', 'verified', 'previous_state_hash', 'state_hash' ),
			'additionalProperties' => false,
		),
		'execute_callback'    => 'wpagent_exec_set_alt_text',
		'permission_callback' => 'wpagent_perm_edit_posts',
		'meta'                => array(
			'show_in_rest' => true,
			'annotations'  => array(
				'readonly'    => false,
				'destructive' => false,
				'idempotent'  => false,
			),
		),
	);
}

/** @param array<int,string> $meta_values */
function wpagent_attachment_alt_state_hash( WP_Post $attachment, array $meta_values ): string {
	return hash(
		'sha256',
		"wpagently-attachment-alt-state-v1\0" . serialize(
			array(
				'post_state_hash' => wpagent_post_state_hash( $attachment ),
				'alt_meta_values' => array_values( $meta_values ),
			)
		)
	);
}

/** @return array{exists:bool,meta_id:int,raw:string,values:array<int,string>,alt:string,state_hash:string}|WP_Error */
function wpagent_attachment_alt_snapshot( WP_Post $attachment ) {
	global $wpdb;
	$rows = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s ORDER BY meta_id ASC",
			$attachment->ID,
			'_wp_attachment_image_alt'
		),
		ARRAY_A
	);
	if ( '' !== (string) $wpdb->last_error || ! is_array( $rows ) || count( $rows ) > 1 ) {
		return new WP_Error( 'wpagent_alt_text_ambiguous', __( 'Der Alt-Text-Metazustand ist nicht eindeutig. Die Änderung wurde nicht ausgeführt.', 'wp-agent-companion' ), array( 'status' => 409 ) );
	}
	if ( array() === $rows ) {
		$values = array();
		$raw    = '';
		$meta_id = 0;
	} else {
		$row = $rows[0];
		$raw = $row['meta_value'] ?? null;
		$meta_id = (int) ( $row['meta_id'] ?? 0 );
		if ( ! is_string( $raw ) || $meta_id < 1 ) {
			return new WP_Error( 'wpagent_alt_text_ambiguous', __( 'Der Alt-Text-Metazustand ist nicht eindeutig. Die Änderung wurde nicht ausgeführt.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$values = array( $raw );
	}
	return array(
		'exists'     => 0 !== $meta_id,
		'meta_id'    => $meta_id,
		'raw'        => $raw,
		'values'     => $values,
		'alt'        => isset( $values[0] ) ? $values[0] : '',
		'state_hash' => wpagent_attachment_alt_state_hash( $attachment, $values ),
	);
}

/** @return array{attachment:WP_Post,snapshot:array{values:array<int,string>,alt:string,state_hash:string}}|WP_Error */
function wpagent_attachment_alt_current( int $attachment_id ) {
	clean_post_cache( $attachment_id );
	wp_cache_delete( $attachment_id, 'post_meta' );
	$attachment = get_post( $attachment_id );
	if ( ! $attachment ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	if ( 'attachment' !== $attachment->post_type ) {
		return new WP_Error( 'wpagent_no_media', __( 'Medienbeitrag nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	$snapshot = wpagent_attachment_alt_snapshot( $attachment );
	return is_wp_error( $snapshot ) ? $snapshot : array( 'attachment' => $attachment, 'snapshot' => $snapshot );
}

/** @param array{attachment:WP_Post,snapshot:array{exists:bool,meta_id:int,raw:string,values:array<int,string>,alt:string,state_hash:string}}|null $current */
function wpagent_alt_text_recovery_required( int $attachment_id, string $previous_hash, ?array $current, string $reason ): WP_Error {
	return new WP_Error(
		'wpagent_alt_text_recovery_required',
		__( 'Der Alt-Text konnte nicht vollständig verifiziert werden. Prüfe das Medium manuell und lies seinen state_hash neu.', 'wp-agent-companion' ),
		array(
			'status'              => 500,
			'attachment_id'       => $attachment_id,
			'previous_state_hash' => $previous_hash,
			'current_state_hash'  => is_array( $current ) ? $current['snapshot']['state_hash'] : '',
			'rolled_back'         => false,
			'rollback_verified'   => false,
			'recovery_required'   => true,
			'reason'              => $reason,
		)
	);
}

/**
 * Replaces an existing exact metadata row only while both its row identity and
 * raw old value still match. This is the mutation CAS, not a pre-write PHP
 * check, so a same-key writer cannot be overwritten between read and write.
 *
 * @param array{exists:bool,meta_id:int,raw:string,values:array<int,string>,alt:string,state_hash:string} $before
 */
function wpagent_alt_text_replace_if_current( int $attachment_id, array $before, string $candidate ): bool {
	global $wpdb;
	if ( ! $before['exists'] || $before['meta_id'] < 1 ) {
		return false;
	}
	$updated = $wpdb->query(
		$wpdb->prepare(
			"UPDATE {$wpdb->postmeta} SET meta_value = %s WHERE meta_id = %d AND post_id = %d AND meta_key = %s AND HEX(meta_value) = HEX(%s)",
			$candidate,
			$before['meta_id'],
			$attachment_id,
			'_wp_attachment_image_alt',
			$before['raw']
		)
	);
	if ( 1 !== $updated ) {
		return false;
	}
	wp_cache_delete( $attachment_id, 'post_meta' );
	return true;
}

/**
 * Uses Core's unique add path, then proves that this request owns exactly one
 * newly inserted row. A missing database uniqueness constraint means a
 * failed add is never treated as a safe no-op after a concurrent writer.
 *
 * @return int|false Newly inserted meta ID, otherwise false.
 */
function wpagent_alt_text_insert_if_absent( int $attachment_id, string $candidate ): int|false {
	$meta_id = add_post_meta( $attachment_id, '_wp_attachment_image_alt', $candidate, true );
	if ( ! is_int( $meta_id ) || $meta_id < 1 ) {
		return false;
	}
	wp_cache_delete( $attachment_id, 'post_meta' );
	return $meta_id;
}

/** @param array{exists:bool,meta_id:int,raw:string,values:array<int,string>,alt:string,state_hash:string} $before */
function wpagent_alt_text_fail_after_uncertain_write( int $attachment_id, string $candidate, array $before ): WP_Error {
	$current = wpagent_attachment_alt_current( $attachment_id );
	if ( is_wp_error( $current ) ) {
		return wpagent_alt_text_recovery_required( $attachment_id, $before['state_hash'], null, 'readback_failed' );
	}
	if ( hash_equals( $before['state_hash'], $current['snapshot']['state_hash'] ) ) {
		return new WP_Error( 'wpagent_alt_text_failed', __( 'Alt-Text konnte nicht gesetzt werden.', 'wp-agent-companion' ), array( 'status' => 500, 'rolled_back' => false, 'rollback_verified' => false, 'recovery_required' => false ) );
	}
	return wpagent_alt_text_recovery_required( $attachment_id, $before['state_hash'], $current, 'conditional_write_not_confirmed' );
}

/**
 * @param mixed $input
 * @return array|WP_Error
 */
function wpagent_exec_set_alt_text( $input ) {
	$input         = is_array( $input ) ? $input : array();
	$attachment_id = (int) ( $input['attachment_id'] ?? 0 );
	$alt           = $input['alt'] ?? null;
	if ( ! is_string( $alt ) || wpagent_alt_text_character_length( $alt ) > WPAGENT_ALT_TEXT_MAX_LENGTH ) {
		return new WP_Error( 'wpagent_alt_text_invalid', __( 'alt muss ein Text mit höchstens 1.000 Zeichen sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	$attachment = get_post( $attachment_id );
	if ( ! $attachment ) {
		return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
	}
	if ( 'attachment' !== $attachment->post_type ) {
		return new WP_Error( 'wpagent_no_media', __( 'Medienbeitrag nicht gefunden.', 'wp-agent-companion' ), array( 'status' => 404 ) );
	}
	$expected_state_hash = is_string( $input['expected_state_hash'] ?? null ) ? strtolower( $input['expected_state_hash'] ) : '';
	if ( 1 !== preg_match( '/^[a-f0-9]{64}$/D', $expected_state_hash ) ) {
		return new WP_Error( 'wpagent_attachment_expected_hash', __( 'expected_state_hash muss der vollständige state_hash aus list-media sein.', 'wp-agent-companion' ), array( 'status' => 400 ) );
	}
	$lock = wpagent_update_post_acquire_lock( $attachment_id );
	if ( is_wp_error( $lock ) ) {
		return $lock;
	}
	try {
		$current = wpagent_attachment_alt_current( $attachment_id );
		if ( is_wp_error( $current ) ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		$previous_hash = $current['snapshot']['state_hash'];
		if ( ! hash_equals( $expected_state_hash, $previous_hash ) ) {
			return new WP_Error( 'wpagent_attachment_conflict', __( 'Das Medium oder sein Alt-Text wurde seit dem Lesen verändert. Lies es neu und wiederhole den Vorgang mit dem aktuellen state_hash.', 'wp-agent-companion' ), array( 'status' => 409, 'current_state_hash' => $previous_hash ) );
		}
		if ( ! wpagent_update_post_refresh_lock( $attachment_id, $lock ) ) {
			return new WP_Error( 'wpagent_attachment_busy', __( 'Die exklusive Mediensperre ging vor dem Schreiben verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		if ( $current['snapshot']['values'] === array( $alt ) ) {
			$confirm = wpagent_attachment_alt_current( $attachment_id );
			if ( is_wp_error( $confirm ) || ! hash_equals( $expected_state_hash, is_array( $confirm ) ? $confirm['snapshot']['state_hash'] : '' ) || ! wpagent_update_post_lock_is_owned( $attachment_id, $lock ) ) {
				return new WP_Error( 'wpagent_attachment_conflict', __( 'Das Medium änderte sich während der No-op-Prüfung.', 'wp-agent-companion' ), array( 'status' => 409 ) );
			}
			return array( 'attachment_id' => $attachment_id, 'alt' => $alt, 'verified' => true, 'previous_state_hash' => $previous_hash, 'state_hash' => $previous_hash );
		}
		// Check capability and lock immediately before the database CAS. A prior
		// authorization answer is not valid across lock-held work.
		if ( ! current_user_can( 'edit_post', $attachment_id ) ) {
			return new WP_Error( 'wpagent_forbidden', __( 'Keine Berechtigung.', 'wp-agent-companion' ), array( 'status' => 403 ) );
		}
		if ( ! wpagent_update_post_refresh_lock( $attachment_id, $lock ) ) {
			return new WP_Error( 'wpagent_attachment_busy', __( 'Die exklusive Mediensperre ging vor dem Schreiben verloren.', 'wp-agent-companion' ), array( 'status' => 409 ) );
		}
		$written_meta_id = $current['snapshot']['exists']
			? ( wpagent_alt_text_replace_if_current( $attachment_id, $current['snapshot'], $alt ) ? $current['snapshot']['meta_id'] : false )
			: wpagent_alt_text_insert_if_absent( $attachment_id, $alt );
		if ( false === $written_meta_id ) {
			return wpagent_alt_text_fail_after_uncertain_write( $attachment_id, $alt, $current['snapshot'] );
		}
		$fresh = wpagent_attachment_alt_current( $attachment_id );
		$candidate_hash = wpagent_attachment_alt_state_hash( is_array( $fresh ) ? $fresh['attachment'] : $current['attachment'], array( $alt ) );
		if ( is_wp_error( $fresh ) || $fresh['snapshot']['meta_id'] !== $written_meta_id || $fresh['snapshot']['values'] !== array( $alt ) || ! hash_equals( $candidate_hash, $fresh['snapshot']['state_hash'] ) || ! wpagent_update_post_lock_is_owned( $attachment_id, $lock ) || ! current_user_can( 'edit_post', $attachment_id ) ) {
			return wpagent_alt_text_recovery_required( $attachment_id, $previous_hash, is_array( $fresh ) ? $fresh : null, 'write_readback_or_lock_failed' );
		}
		return array( 'attachment_id' => $attachment_id, 'alt' => $alt, 'verified' => true, 'previous_state_hash' => $previous_hash, 'state_hash' => $fresh['snapshot']['state_hash'] );
	} finally {
		wpagent_update_post_release_lock( $attachment_id, $lock );
	}
}
