<?php

namespace Fotogenic_AI;

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

final class Image_Source_Resolver {
    private static ?Image_Source_Resolver $instance = null;
    private const MAX_IMAGES = 4;
    private const CAMPAIGN_MAX_IMAGES = 10;
    private const MAX_IMAGE_BYTES = 26214400;
    private const WORKFLOW_IMAGE_MIME_TYPES = [ 'image/jpeg', 'image/png', 'image/webp' ];

    private function __construct() {}

    public static function instance(): Image_Source_Resolver {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

	/** @return array|\WP_Error */
	public function get_image_files_for_attachments( array $image_ids ) {
        $image_ids = array_values( array_unique( array_filter( array_map( 'absint', $image_ids ) ) ) );
        $image_ids = array_slice( $image_ids, 0, self::MAX_IMAGES );
        if ( empty( $image_ids ) ) {
            return new \WP_Error( 'fotogenic_ai_no_images', __( 'Please add at least one product image.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }

        $image_files = [];
        foreach ( $image_ids as $attachment_id ) {
			$resolved = $this->get_image_file_for_workflow_attachment( $attachment_id );
            if ( is_wp_error( $resolved ) ) {
                return $resolved;
            }
            $image_files[] = $resolved;
        }

        return $image_files;
    }

    /**
     * Resolve the Campaign Set source list without changing the standard four-image limit.
     *
     * @param array $image_ids Attachment IDs.
     * @return array|\WP_Error
     */
    public function get_campaign_image_files_for_attachments( array $image_ids ) {
        $image_ids = array_values( array_unique( array_filter( array_map( 'absint', $image_ids ) ) ) );
        if ( empty( $image_ids ) ) {
            return new \WP_Error( 'fotogenic_ai_no_images', __( 'Please add at least one product image.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }
        if ( count( $image_ids ) > self::CAMPAIGN_MAX_IMAGES ) {
            return new \WP_Error( 'fotogenic_ai_too_many_images', __( 'Select up to 10 product images for Campaign Set.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }

        $image_files = [];
        foreach ( $image_ids as $attachment_id ) {
            $resolved = $this->get_image_file_for_workflow_attachment( $attachment_id );
            if ( is_wp_error( $resolved ) ) {
                return $resolved;
            }
            $image_files[] = $resolved;
        }

        return $image_files;
    }

    /**
     * Resolve the single source accepted by Increase Resolution.
     *
     * @param int $attachment_id Attachment ID.
     * @return array|\WP_Error
     */
    public function get_enhance_image_file_for_attachment( int $attachment_id ) {
        return $this->get_image_file_for_workflow_attachment( $attachment_id );
    }

    /** @return array|\WP_Error */
    public function get_image_file_for_attachment( int $attachment_id ) {
        if ( $attachment_id <= 0 || 'attachment' !== get_post_type( $attachment_id ) ) {
            return new \WP_Error( 'fotogenic_ai_invalid_attachment', __( 'Invalid image attachment.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }
        if ( ! wp_attachment_is_image( $attachment_id ) ) {
            return new \WP_Error( 'fotogenic_ai_invalid_attachment', __( 'Attachment must be an image.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }
        $file_path = $this->resolve_source_file_path( $attachment_id );
        if ( is_wp_error( $file_path ) ) {
            return $file_path;
        }

        $file_size = filesize( $file_path );
        if ( false === $file_size || $file_size <= 0 ) {
            return new \WP_Error( 'fotogenic_ai_image_read_failed', __( 'Failed to read image file.', 'fotogenic-ai' ), [ 'status' => 500 ] );
        }
        if ( $file_size > self::MAX_IMAGE_BYTES ) {
            return new \WP_Error( 'fotogenic_ai_image_too_large', __( 'Select an image no larger than 25 MiB.', 'fotogenic-ai' ), [ 'status' => 400 ] );
        }

        $mime = get_post_mime_type( $attachment_id );
        if ( ! is_string( $mime ) || '' === $mime ) {
            $mime = wp_get_image_mime( $file_path );
        }
		if ( ! is_string( $mime ) || ! in_array( $mime, self::WORKFLOW_IMAGE_MIME_TYPES, true ) ) {
			return new \WP_Error(
				'fotogenic_ai_unsupported_image_type',
				__( 'Fotogenic AI supports JPEG, PNG, and WebP images.', 'fotogenic-ai' ),
				[ 'status' => 400 ]
			);
        }

        return [
            'attachment_id' => $attachment_id,
            'path'          => $file_path,
            'mime'          => $mime,
            'bytes'         => (int) $file_size,
            'filename'      => wp_basename( $file_path ),
        ];
    }

    /** @return array|\WP_Error */
    public function get_image_file_for_workflow_attachment( int $attachment_id ) {
        $resolved = $this->get_image_file_for_attachment( $attachment_id );
        if ( is_wp_error( $resolved ) ) {
            return $resolved;
        }

        $detected_mime = wp_get_image_mime( (string) $resolved['path'] );
		if ( ! is_string( $detected_mime ) || ! in_array( $detected_mime, self::WORKFLOW_IMAGE_MIME_TYPES, true ) ) {
            return new \WP_Error(
                'fotogenic_ai_unsupported_image_type',
				__( 'Fotogenic AI supports JPEG, PNG, and WebP images.', 'fotogenic-ai' ),
                [ 'status' => 400 ]
            );
        }

        $resolved['mime'] = $detected_mime;
        return $resolved;
    }

	/**
	 * Return browser-safe workflow eligibility without exposing a local path.
	 *
	 * @return array{eligible: bool, eligibilityReason: string, bytes: int, mime: string}
	 */
	public function get_workflow_attachment_eligibility( int $attachment_id ): array {
		$resolved = $this->get_image_file_for_workflow_attachment( $attachment_id );
		if ( is_wp_error( $resolved ) ) {
			return [
				'eligible'          => false,
				'eligibilityReason' => (string) $resolved->get_error_message(),
				'bytes'             => 0,
				'mime'              => '',
			];
		}

		return [
			'eligible'          => true,
			'eligibilityReason' => '',
			'bytes'             => (int) ( $resolved['bytes'] ?? 0 ),
			'mime'              => (string) ( $resolved['mime'] ?? '' ),
		];
	}

    /** @return string|\WP_Error */
    private function resolve_source_file_path( int $attachment_id ) {
        $original = function_exists( 'wp_get_original_image_path' )
            ? wp_get_original_image_path( $attachment_id )
            : '';
        $attached = get_attached_file( $attachment_id );
        $paths    = array_values(
            array_unique(
                array_filter(
                    [ is_string( $original ) ? $original : '', is_string( $attached ) ? $attached : '' ]
                )
            )
        );

        foreach ( $paths as $path ) {
            if ( ! file_exists( $path ) ) {
                continue;
            }
            if ( ! is_readable( $path ) ) {
                return new \WP_Error(
                    'fotogenic_ai_image_read_failed',
                    __( 'The selected image file cannot be read.', 'fotogenic-ai' ),
                    [ 'status' => 500 ]
                );
            }
            return $path;
        }

        return new \WP_Error(
            'fotogenic_ai_image_missing',
            __( 'The selected image file is missing. Replace or remove it to continue.', 'fotogenic-ai' ),
            [ 'status' => 404 ]
        );
    }
}
