using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using XPrintServer.Business.Dto;
using XPrintServer.Business.Services.Interface;
using XPrintServer.Business.Workflows;
using XPrintServer.Business.Workflows.Configure;
using Workflow = XPrintServer.Business.Workflows.Workflow;

namespace XPrintServer.Business.Services
{
    public class ComfyUIService
    {
        //private static string _workflowPath = @"J:\ComfyUI_windows_portable_nvidia\ComfyUI_windows_portable\ComfyUI\user\default\workflows\qwen-image_workflow.json";
        //private static string _saveTempPath = @"J:\ComfyUI_windows_portable_nvidia\ComfyUI_windows_portable\ComfyUI\temp";


        public QwenWorkflow QwenWorkflow { get; set; }
        public SplitImageWorkflow SplitImageWorkflow { get; set; }

        protected HttpClient httpClient = new HttpClient();
        // 构造函数初始化HTTP客户端和API地址
        public ComfyUIService(ComfyUIInfos infos)
        {
            QwenWorkflow = new QwenWorkflow(infos);
            SplitImageWorkflow = new SplitImageWorkflow(infos);
        }


        public async Task<string> GetGenerationResult(string promptId, string outputId)
        {
            HttpResponseMessage response = await httpClient!.GetAsync(
                $"{Workflow.apiBaseUrl}/history/{promptId}");

            if (!response.IsSuccessStatusCode)
                throw new Exception("获取结果失败");

            string responseContent = await response.Content.ReadAsStringAsync();
            dynamic result = JsonConvert.DeserializeObject(responseContent)!;
            dynamic thisResult = result[promptId];
            if (thisResult == null)
            {
                return string.Empty;
            }
            if (thisResult.status["status_str"] == "success")
            {
                var image = thisResult.outputs[outputId]["images"][0];
                string subFolder = image.subfolder;
                string fileName = image.filename;
                if (!string.IsNullOrWhiteSpace(fileName))
                {
                    string imagePath = Path.Combine(Workflow.SaveTempPath, subFolder, fileName);
                    return imagePath;
                }
            }
            else if (thisResult.status["status_str"] == "error")
            {
                throw new Exception($"生成失败: {result.error}");
            }
            return string.Empty;
        }

        public async Task<string> GetGenerationResult(WorkflowType workflowType, string promptId)
        {
            switch (workflowType)
            {
                case WorkflowType.Qwen:
                    return await GetGenerationResult(promptId, "102");

                case WorkflowType.SplitImage:
                    return await GetGenerationResult(promptId, "4");
                default:

                    return string.Empty;
            }
        }
    }
}
