"""Operator to remove all pending workflows from ComfyUI server queue."""
import logging
import requests

import bpy

from ..utils import add_custom_headers, get_server_url

log = logging.getLogger("comfyui_blender")


class ComfyBlenderOperatorStopWorkflow(bpy.types.Operator):
    """Operator to remove all pending workflows from ComfyUI server queue."""

    bl_idname = "comfy.clear_queue"
    bl_label = "Clear Queue"
    bl_description = "Remove all pending workflows from ComfyUI server queue."

    def execute(self, context):
        """Execute the operator."""

        # Get add-on preferences
        addon_prefs = context.preferences.addons["comfyui_blender"].preferences

        # Send clear queue request to ComfyUI server
        data = {"clear": True}
        url = get_server_url("/queue")
        headers = {"Content-Type": "application/json"}
        headers = add_custom_headers(headers)
        try:
            response = requests.post(url, json=data, headers=headers)
        except Exception as e:
            error_message = f"Failed to send clear queue request to ComfyUI server: {addon_prefs.server_address}. {e}"
            log.exception(error_message)
            bpy.ops.comfy.show_error_popup("INVOKE_DEFAULT", error_message=error_message)
            return {'CANCELLED'}

        if response.status_code != 200:
            error_message = response.text
            log.error(error_message)
            bpy.ops.comfy.show_error_popup("INVOKE_DEFAULT", error_message=error_message)
            return {'CANCELLED'}

        # Get indices of workflows to remove and remove them in reverse order
        queue = addon_prefs.queue
        workflow_indices = [i for i, workflow in enumerate(queue) if workflow.status == "pending"]
        for i in reversed(workflow_indices):
            queue.remove(i)

        self.report({'INFO'}, "Request to stop workflow execution sent to ComfyUI server.")
        return {'FINISHED'}


def register():
    """Register the operator."""

    bpy.utils.register_class(ComfyBlenderOperatorStopWorkflow)


def unregister():
    """Unregister the operator."""

    bpy.utils.unregister_class(ComfyBlenderOperatorStopWorkflow)
