<?php

namespace Fotogenic_AI;

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

/**
 * Builds the final Increase Resolution multipart boundary from normalized data.
 */
final class Increase_Resolution_Multipart_Builder {
	/**
	 * @param array $command Already-normalized service data and one resolved file descriptor.
	 * @return array{fields: array, files: array}|\WP_Error
	 */
	public function build( array $command ) {
		$command = Workflow_Contract_Guard::finalize( $command );
		if ( is_wp_error( $command ) ) {
			return $command;
		}

		$unknown = array_values( array_diff( array_keys( $command ), [ 'source_image' ] ) );
		if ( ! empty( $unknown ) || ! $this->is_file_descriptor( $command['source_image'] ?? null ) ) {
			return new \WP_Error(
				'fotogenic_ai_invalid_enhance_multipart',
				__( 'Increase Resolution requires exactly one resolved source image.', 'fotogenic-ai' ),
				[
					'status' => 400,
					'fields' => $unknown,
				]
			);
		}

		return [
			'fields' => [],
			'files'  => [ 'image' => $command['source_image'] ],
		];
	}

	/**
	 * @param mixed $value Resolved file descriptor.
	 */
	private function is_file_descriptor( $value ): bool {
		return is_array( $value )
			&& isset( $value['path'], $value['filename'], $value['mime'], $value['bytes'] );
	}
}
