<?php
/**
 * Recovery helpers for native WordPress REST publication.
 *
 * @package Contentosapp_Studio
 * @since   1.0.1
 */

defined( 'ABSPATH' ) || exit;

class Costudio_Publication_Recovery {

	public static function marker( string $idempotency_key ): string {
		return '<!-- costudio-idempotency:' . $idempotency_key . ' -->';
	}

	public static function ensure_marker( string $content, string $idempotency_key ): string {
		$marker = self::marker( $idempotency_key );
		return false !== strpos( $content, $marker ) ? $content : rtrim( $content ) . "\n\n" . $marker;
	}

	public static function strip_markers( string $content ): string {
		if ( '' === $content || false === strpos( $content, 'costudio-idempotency:' ) ) {
			return $content;
		}

		$content = preg_replace(
			'/<!--\s*wp:html\s*-->\s*<!--\s*costudio-idempotency:[a-f0-9]{64}\s*-->\s*<!--\s*\/wp:html\s*-->/is',
			'',
			$content
		) ?? $content;

		$content = preg_replace(
			'/<!--\s*wp:paragraph\s*-->\s*<p>\s*costudio-idempotency:[a-f0-9]{64}\s*<\/p>\s*<!--\s*\/wp:paragraph\s*-->/is',
			'',
			$content
		) ?? $content;

		$content = preg_replace(
			'/<!--\s*costudio-idempotency:[a-f0-9]{64}\s*-->/i',
			'',
			$content
		) ?? $content;

		$content = preg_replace(
			'/(?:<p>)?\s*costudio-idempotency:[a-f0-9]{64}\s*(?:<\/p>)?/i',
			'',
			$content
		) ?? $content;

		return trim( preg_replace( "/\n{3,}/", "\n\n", $content ) ?? $content );
	}

	public static function find_local_post( string $idempotency_key ): ?array {
		// Using WP_Query with meta_query instead of get_posts() with meta_key/meta_value
		// to follow WordPress Coding Standards. The meta query is intentional and the key
		// (_costudio_idempotency_key) is always a unique SHA-256 hash (max 1 result).
		$query = new WP_Query(
			[
				'post_type'      => 'post',
				'post_status'    => 'any',
				'posts_per_page' => 1,
				'fields'         => 'ids',
				'no_found_rows'  => true,
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
				'meta_query'     => [
					[
						'key'     => '_costudio_idempotency_key',
						'value'   => $idempotency_key,
						'compare' => '=',
					],
				],
			]
		);
		if ( empty( $query->posts[0] ) ) {
			return null;
		}
		$post_id = (int) $query->posts[0];
		return [
			'id'       => $post_id,
			'link'     => (string) get_permalink( $post_id ),
			'edit_url' => admin_url( "post.php?post={$post_id}&action=edit" ),
			'title'    => get_the_title( $post_id ),
		];
	}

	public static function find_remote_post( string $site_url, string $auth, string $idempotency_key, int $attempts = 1 ): ?array {
		$attempts = max( 1, min( 4, $attempts ) );
		$marker   = self::marker( $idempotency_key );
		for ( $attempt = 1; $attempt <= $attempts; $attempt++ ) {
			$url = add_query_arg( [
				'context'  => 'edit',
				'status'   => 'any',
				'search'   => $idempotency_key,
				'per_page' => 10,
				'_fields'  => 'id,link,title,content,date,date_gmt,modified,modified_gmt',
			], rtrim( $site_url, '/' ) . '/wp-json/wp/v2/posts' );
			$response = wp_safe_remote_get( $url, costudio_safe_remote_args( [
				'timeout' => 15,
				'headers' => [ 'Authorization' => $auth ],
			] ) );
			if ( ! is_wp_error( $response ) && 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
				$rows = json_decode( wp_remote_retrieve_body( $response ), true );
				foreach ( is_array( $rows ) ? $rows : [] as $row ) {
					$raw = (string) ( $row['content']['raw'] ?? $row['content']['rendered'] ?? '' );
					if ( false !== strpos( $raw, $marker ) ) {
						return $row;
					}
				}
			}
			if ( $attempt < $attempts ) {
				usleep( $attempt * 500000 );
			}
		}
		return null;
	}
}
