package com.backendsys.modules.sdk.comfyui.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.modules.sdk.comfyui.entity.ComfyuiResponse;
import com.backendsys.modules.sdk.comfyui.entity.ComfyuiText2Image;
import com.backendsys.modules.sdk.comfyui.enums.TaskTypeEnums;
import com.backendsys.modules.sdk.comfyui.service.ComfyuiService;
import com.backendsys.modules.sdk.comfyui.service.ComfyuiText2ImageService;
import com.backendsys.modules.sdk.comfyui.utils.ComfyuiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class ComfyuiText2ImageServiceImpl implements ComfyuiText2ImageService {

    @Autowired
    private ComfyuiUtil comfyuiUtil;

    @Autowired
    private ComfyuiService comfyuiService;

    /**
     * [ComfyUI] 文生图 (7.16生图.json)
     * // ComfyuiResponse -> void
     */
    @Override
    public Long generateText2Image(String client_id, ComfyuiText2Image comfyuiText2Image) {

        String prompt = "{"+
                "  \"3\": {"+
                "    \"inputs\": {"+
                "      \"text\": ["+
                "        \"120\","+
                "        0"+
                "      ],"+
                "      \"speak_and_recognation\": {"+
                "        \"__value__\": ["+
                "          false,"+
                "          true"+
                "        ]"+
                "      },"+
                "      \"clip\": ["+
                "        \"151\","+
                "        1"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"CLIPTextEncode\","+
                "    \"_meta\": {"+
                "      \"title\": \"CLIP文本编码\""+
                "    }"+
                "  },"+
                "  \"13\": {"+
                "    \"inputs\": {"+
                "      \"guidance\": " + comfyuiText2Image.getPrompt_flux_guidance() + ","+
                "      \"conditioning\": ["+
                "        \"3\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"FluxGuidance\","+
                "    \"_meta\": {"+
                "      \"title\": \"Flux引导\""+
                "    }"+
                "  },"+
                "  \"15\": {"+
                "    \"inputs\": {"+
                "      \"model\": ["+
                "        \"152\","+
                "        0"+
                "      ],"+
                "      \"conditioning\": ["+
                "        \"13\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"BasicGuider\","+
                "    \"_meta\": {"+
                "      \"title\": \"基本引导器\""+
                "    }"+
                "  },"+
                "  \"31\": {"+
                "    \"inputs\": {"+
                "      \"samples\": ["+
                "        \"32\","+
                "        0"+
                "      ],"+
                "      \"vae\": ["+
                "        \"151\","+
                "        2"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"VAEDecode\","+
                "    \"_meta\": {"+
                "      \"title\": \"VAE解码\""+
                "    }"+
                "  },"+
                "  \"32\": {"+
                "    \"inputs\": {"+
                "      \"noise\": ["+
                "        \"37\","+
                "        0"+
                "      ],"+
                "      \"guider\": ["+
                "        \"15\","+
                "        0"+
                "      ],"+
                "      \"sampler\": ["+
                "        \"84\","+
                "        0"+
                "      ],"+
                "      \"sigmas\": ["+
                "        \"150\","+
                "        0"+
                "      ],"+
                "      \"latent_image\": ["+
                "        \"90\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"SamplerCustomAdvanced\","+
                "    \"_meta\": {"+
                "      \"title\": \"自定义采样器（高级）\""+
                "    }"+
                "  },"+
                "  \"37\": {"+
                "    \"inputs\": {"+
                "      \"noise_seed\": " + comfyuiText2Image.getSeed() +
                "    },"+
                "    \"class_type\": \"RandomNoise\","+
                "    \"_meta\": {"+
                "      \"title\": \"随机噪波\""+
                "    }"+
                "  },"+
                "  \"38\": {"+
                "    \"inputs\": {"+
                "      \"text\": \"\","+
                "      \"speak_and_recognation\": {"+
                "        \"__value__\": ["+
                "          false,"+
                "          true"+
                "        ]"+
                "      }"+
                "    },"+
                "    \"class_type\": \"TextInput_\","+
                "    \"_meta\": {"+
                "      \"title\": \"触发词\""+
                "    }"+
                "  },"+
                "  \"51\": {"+
                "    \"inputs\": {"+
                "      \"text\": \"fenjing\","+
                "      \"speak_and_recognation\": {"+
                "        \"__value__\": ["+
                "          false,"+
                "          true"+
                "        ]"+
                "      }"+
                "    },"+
                "    \"class_type\": \"TextInput_\","+
                "    \"_meta\": {"+
                "      \"title\": \"分镜号\""+
                "    }"+
                "  },"+
                "  \"84\": {"+
                "    \"inputs\": {"+
                "      \"sampler_name\": \"" + comfyuiText2Image.getSampler() + "\""+
                "    },"+
                "    \"class_type\": \"KSamplerSelect\","+
                "    \"_meta\": {"+
                "      \"title\": \"K采样器选择\""+
                "    }"+
                "  },"+
                "  \"90\": {"+
                "    \"inputs\": {"+
                "      \"width\": ["+
                "        \"121\","+
                "        0"+
                "      ],"+
                "      \"height\": ["+
                "        \"122\","+
                "        0"+
                "      ],"+
                "      \"batch_size\": " + comfyuiText2Image.getBatch_size() +
                "    },"+
                "    \"class_type\": \"EmptySD3LatentImage\","+
                "    \"_meta\": {"+
                "      \"title\": \"空Latent图像（SD3）\""+
                "    }"+
                "  },"+
                "  \"91\": {"+
                "    \"inputs\": {"+
                "      \"filename_prefix\": ["+
                "        \"51\","+
                "        0"+
                "      ],"+
                "      \"images\": ["+
                "        \"31\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"SaveImage\","+
                "    \"_meta\": {"+
                "      \"title\": \"保存图像\""+
                "    }"+
                "  },"+
                "  \"120\": {"+
                "    \"inputs\": {"+
                "      \"text_0\": \", a pig\","+
                "      \"text\": ["+
                "        \"148\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"PandasShowText\","+
                "    \"_meta\": {"+
                "      \"title\": \"Pandas Show Text\""+
                "    }"+
                "  },"+
                "  \"121\": {"+
                "    \"inputs\": {"+
                "      \"value\": " + comfyuiText2Image.getWidth() +
                "    },"+
                "    \"class_type\": \"easy int\","+
                "    \"_meta\": {"+
                "      \"title\": \"整数\""+
                "    }"+
                "  },"+
                "  \"122\": {"+
                "    \"inputs\": {"+
                "      \"value\": " + comfyuiText2Image.getHeight() +
                "    },"+
                "    \"class_type\": \"easy int\","+
                "    \"_meta\": {"+
                "      \"title\": \"整数\""+
                "    }"+
                "  },"+
                "  \"146\": {"+
                "    \"inputs\": {"+
                "      \"from_translate\": \"auto\","+
                "      \"to_translate\": \"english\","+
                "      \"add_proxies\": false,"+
                "      \"proxies\": \"\","+
                "      \"auth_data\": \"\","+
                "      \"service\": \"BaiduTranslator [appid and appkey]\","+
                "      \"text\": ["+
                "        \"153\","+
                "        0"+
                "      ],"+
                "      \"Show proxy\": \"proxy_hide\","+
                "      \"Show authorization\": \"authorization_hide\","+
                "      \"speak_and_recognation\": {"+
                "        \"__value__\": ["+
                "          false,"+
                "          true"+
                "        ]"+
                "      }"+
                "    },"+
                "    \"class_type\": \"DeepTranslatorTextNode\","+
                "    \"_meta\": {"+
                "      \"title\": \"Deep Translator Text Node\""+
                "    }"+
                "  },"+
                "  \"148\": {"+
                "    \"inputs\": {"+
                "      \"delimiter\": \", \","+
                "      \"string1\": ["+
                "        \"38\","+
                "        0"+
                "      ],"+
                "      \"string2\": ["+
                "        \"146\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"JoinStrings\","+
                "    \"_meta\": {"+
                "      \"title\": \"Join Strings\""+
                "    }"+
                "  },"+
                "  \"150\": {"+
                "    \"inputs\": {"+
                "      \"scheduler\": \"normal\","+
                "      \"steps\": " + comfyuiText2Image.getStep() + ","+
                "      \"denoise\": 1,"+
                "      \"model\": ["+
                "        \"152\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"BasicScheduler\","+
                "    \"_meta\": {"+
                "      \"title\": \"基本调度器\""+
                "    }"+
                "  },"+
                "  \"151\": {"+
                "    \"inputs\": {"+
                "      \"ckpt_name\": \"" + comfyuiText2Image.getModel_name() + "\""+
                "    },"+
                "    \"class_type\": \"CheckpointLoaderSimple\","+
                "    \"_meta\": {"+
                "      \"title\": \"Checkpoint加载器（简易）\""+
                "    }"+
                "  },"+
                "  \"152\": {"+
                "    \"inputs\": {"+
                "      \"lora_name\": \"【FLUX】都市高武推文 _ 异能 法术 战斗_v1.0.safetensors\","+
                "      \"strength_model\": 0,"+
                "      \"model\": ["+
                "        \"151\","+
                "        0"+
                "      ]"+
                "    },"+
                "    \"class_type\": \"LoraLoaderModelOnly\","+
                "    \"_meta\": {"+
                "      \"title\": \"LoRA加载器（仅模型）\""+
                "    }"+
                "  },"+
                "  \"153\": {"+
                "    \"inputs\": {"+
                "      \"text\": \"" + comfyuiText2Image.getPrompt_text() + "\","+
                "      \"speak_and_recognation\": {"+
                "        \"__value__\": ["+
                "          false,"+
                "          true"+
                "        ]"+
                "      }"+
                "    },"+
                "    \"class_type\": \"TextInput_\","+
                "    \"_meta\": {"+
                "      \"title\": \"Text Input ♾️Mixlab\""+
                "    }"+
                "  }"+
                "}"
        ;

        // [DB] 初始化任务
        Long task_id = comfyuiUtil.initComfyuiTask(client_id, prompt, TaskTypeEnums.TEXT_2_IMAGE.getValue());
        return task_id;

//        // [ComfyUI] 执行任务
//        JSONObject prompt_object = JSONUtil.parseObj(prompt);
//        Mono<ComfyuiResponse> cfPromptResponseMono = comfyuiService.prompt(client_id, prompt_object);
//        ComfyuiResponse response = cfPromptResponseMono.block();
//        response.setClient_id(client_id);
//
//        return response;
    }


    /**
     * [ComfyUI] 文生图 (基础生图)
     * // ComfyuiResponse -> void
     */
    @Override
    public Long generateText2ImageSimple(String client_id, ComfyuiText2Image comfyuiText2Image) {

        // [ComfyUI-基础生图]
        String prompt = "{" +
                    "\"3\": {" +
                        "\"inputs\": {" +
//                            "\"seed\": 449753344472378," +
                            "\"seed\": " + comfyuiText2Image.getSeed() + "," +
//                            "\"steps\": 20," +
                            "\"steps\": " + comfyuiText2Image.getStep() + "," +
                            "\"cfg\": 8," +
//                            "\"sampler_name\": \"euler\"," +
                            "\"sampler_name\": \"" + comfyuiText2Image.getSampler() + "\"," +
                            "\"scheduler\": \"normal\", \"denoise\": 1," +
                            "\"model\": [\"4\", 0], \"positive\": [\"6\", 0]," +
                            "\"negative\": [\"7\", 0], \"latent_image\": [\"5\", 0]" +
                        "}," +
                        "\"class_type\": \"KSampler\", \"_meta\": { \"title\": \"K采样器\" }" +
                    "}," +
                    "\"4\": {" +
                        "\"inputs\": {" +
//                            "\"ckpt_name\": \"v1-5-pruned-emaonly-fp16.safetensors\"" +
                            "\"ckpt_name\": \"" + comfyuiText2Image.getModel_name() + "\"" +
                        "}," +
                        "\"class_type\": \"CheckpointLoaderSimple\"," +
                        "\"_meta\": { \"title\": \"Checkpoint加载器（简易）\" }" +
                    "}," +
                    "\"5\": {" +
                        "\"inputs\": {" +
//                            "\"width\": 512," +
//                            "\"height\": 512," +
//                            "\"batch_size\": 1" +
                            "\"width\": " + comfyuiText2Image.getWidth() + "," +
                            "\"height\": " + comfyuiText2Image.getHeight() + "," +
                            "\"batch_size\": " + comfyuiText2Image.getBatch_size() +
                        "}," +
                        "\"class_type\": \"EmptyLatentImage\"," +
                        "\"_meta\": { \"title\": \"空Latent图像\" }" +
                    "}," +
                    "\"6\": {" +
                        "\"inputs\": {" +
//                            "\"text\": \"beautiful scenery nature glass bottle landscape, , purple galaxy bottle,\"," +
                            "\"text\": \"" + comfyuiText2Image.getPrompt_text() + "\"," +
                            "\"speak_and_recognation\": { \"__value__\": [false, true] }," +
                            "\"clip\": [\"4\", 1]" +
                        "}," +
                        "\"class_type\": \"CLIPTextEncode\", \"_meta\": { \"title\": \"CLIP文本编码\" }" +
                    "}," +
                    "\"7\": {" +
                        "\"inputs\": {" +
                            "\"text\": \"text, watermark\"," +
                            "\"speak_and_recognation\": { \"__value__\": [false, true] }," +
                            "\"clip\": [\"4\", 1]" +
                        "}," +
                        "\"class_type\": \"CLIPTextEncode\", \"_meta\": { \"title\": \"CLIP文本编码\" }" +
                    "}," +
                    "\"8\": {" +
                        "\"inputs\": {" +
                            "\"samples\": [\"3\", 0], \"vae\": [\"4\", 2]," +
                        "}," +
                        "\"class_type\": \"VAEDecode\", \"_meta\": { \"title\": \"VAE解码\" }" +
                    "}," +
                    "\"9\": {" +
                        "\"inputs\": {" +
                            "\"filename_prefix\": \"ComfyUI\", \"images\": [\"8\", 0]" +
                        "}," +
                        "\"class_type\": \"SaveImage\", \"_meta\": { \"title\": \"保存图像\" }" +
                    "}," +
                "}"
        ;


        // [DB] 初始化任务
        Long task_id = comfyuiUtil.initComfyuiTask(client_id, prompt, TaskTypeEnums.TEXT_2_IMAGE.getValue());
        return task_id;

//        // [ComfyUI] 执行任务
//        JSONObject prompt_object = JSONUtil.parseObj(prompt);
//        Mono<ComfyuiResponse> cfPromptResponseMono = comfyuiService.prompt(client_id, prompt_object);
//        ComfyuiResponse response = cfPromptResponseMono.block();
//        response.setClient_id(client_id);

//        return response;
    }

}
