<?php
/**
 * Image REST Controller
 *
 * Handles image generation and recommendation operations.
 *
 * @package WP_Agentic_Writer
 */

/**
 * Class WP_Agentic_Writer_Controller_Image
 *
 * REST controller for image operations.
 *
 * @since 0.3.0
 */
class WP_Agentic_Writer_Controller_Image
{
    /**
     * Sidebar instance for dependency access.
     *
     * @var WP_Agentic_Writer_Gutenberg_Sidebar
     */
    private $sidebar;

    /**
     * Constructor.
     *
     * @since 0.3.0
     * @param WP_Agentic_Writer_Gutenberg_Sidebar $sidebar Sidebar instance.
     */
    public function __construct($sidebar)
    {
        $this->sidebar = $sidebar;
    }

    /**
     * Handle get image recommendations request.
     *
     * @since 0.1.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_get_image_recommendations($request)
    {
        $post_id = $request->get_param("post_id");

        if ($post_id > 0 && !$this->sidebar->check_post_permission($post_id)) {
            return new WP_Error(
                "forbidden",
                __(
                    "You do not have permission to access this post.",
                    "wp-agentic-writer",
                ),
                ["status" => 403],
            );
        }

        $image_manager = WP_Agentic_Writer_Image_Manager::get_instance();
        $images = $image_manager->get_image_recommendations($post_id);

        // Block-level sync: ensure each unresolved image block has a stable
        // agent id and a corresponding recommendation row.
        if ($post_id > 0) {
            $post = get_post($post_id);
            if ($post instanceof WP_Post && !empty($post->post_content)) {
                $post_config = $this->sidebar->get_post_config($post_id);
                if (!empty($post_config["include_images"])) {
                    $images = $this->sidebar->sync_image_block_recommendations(
                        $post_id,
                        $post,
                    );
                }
            }
        }

        return new WP_REST_Response(["images" => $images], 200);
    }

    /**
     * Handle generate image request.
     *
     * @since 0.1.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_generate_image($request)
    {
        // Check rate limit.
        $rate_limit = WPAW_Rate_Limiter::check("generate_image");
        if (is_wp_error($rate_limit)) {
            return $rate_limit;
        }

        $post_id = $request->get_param("post_id");
        $agent_image_id = $request->get_param("agent_image_id");
        $prompt = $request->get_param("prompt");
        $variant_count = $request->get_param("variant_count") ?? 2;

        if ($post_id > 0 && !$this->sidebar->check_post_permission($post_id)) {
            return new WP_Error(
                "forbidden",
                __(
                    "You do not have permission to edit this post.",
                    "wp-agentic-writer",
                ),
                ["status" => 403],
            );
        }

        $image_manager = WP_Agentic_Writer_Image_Manager::get_instance();
        $variants = $image_manager->generate_image_variants(
            $post_id,
            $agent_image_id,
            $prompt,
            $variant_count,
        );

        if (is_wp_error($variants)) {
            return $variants;
        }

        return new WP_REST_Response(["variants" => $variants], 200);
    }

    /**
     * Handle commit image request.
     *
     * @since 0.1.0
     * @param WP_REST_Request $request REST request.
     * @return WP_REST_Response|WP_Error Response.
     */
    public function handle_commit_image($request)
    {
        $post_id = $request->get_param("post_id");
        $agent_image_id = $request->get_param("agent_image_id");
        $variant_id = $request->get_param("variant_id");
        $alt_text = $request->get_param("alt");

        if ($post_id > 0 && !$this->sidebar->check_post_permission($post_id)) {
            return new WP_Error(
                "forbidden",
                __(
                    "You do not have permission to edit this post.",
                    "wp-agentic-writer",
                ),
                ["status" => 403],
            );
        }

        $image_manager = WP_Agentic_Writer_Image_Manager::get_instance();
        $result = $image_manager->commit_image_variant(
            $post_id,
            $agent_image_id,
            $variant_id,
            $alt_text,
        );

        if (is_wp_error($result)) {
            return $result;
        }

        return new WP_REST_Response($result, 200);
    }
}
