package com.cmvr.test.flow.runtime.operator.llm;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.utils.http.CallAPIUtil;
import com.cmvr.llm.config.APIProperties;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;

@Slf4j
@Service
@RequiredArgsConstructor
public class LLMCurrentPageOperateService implements LLMOperateService {

    private final APIProperties apiProperties;

    @Override
    public boolean supports(ActionEnum action) {
        return action.name().equals("GET_CURRENT_PAGE");
    }

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        JSONObject inputParams = message.getInputParams();

        String fileUrl = inputParams.getString("url");          // 原图片地址
        String targetUrl = apiProperties.getCurrentPage();  // 目标接口地址

        File tempFile = null;
        try {
            // 1. 截取文件名
            String fileName = getFileNameFromUrl(fileUrl);

            // 2. 创建临时文件
            tempFile = File.createTempFile("upload_", "_" + fileName);

            // 3. 下载远程文件到本地临时文件
            HttpUtil.downloadFile(fileUrl, tempFile);

            // 4. 调用上传接口
            String resp = CallAPIUtil.doPostFile(targetUrl, null, "file", tempFile, null);

            JSONObject jsonObject = JSON.parseObject(resp);
            JSONArray results = jsonObject.getJSONArray("results");

            String pageName = null;
            for (Object result : results) {
                JSONObject resultJson = (JSONObject) result;
                if (resultJson.getInteger("rank") == 1) {
                    String filename = resultJson.getString("filename");
                    pageName = filename.substring(0, filename.lastIndexOf("."));
                }
            }

            JSONObject output = new JSONObject();
            output.put("pageName", pageName);

            return TaskNodeExecuteResult.success(output);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (tempFile != null && tempFile.exists()) {
                FileUtil.del(tempFile);
            }
        }
    }

    /**
     * 从 URL 中截取最后的文件名
     */
    private String getFileNameFromUrl(String url) {
        String cleanUrl = url;
        int qIndex = cleanUrl.indexOf("?");
        if (qIndex > -1) {
            cleanUrl = cleanUrl.substring(0, qIndex);
        }
        return cleanUrl.substring(cleanUrl.lastIndexOf("/") + 1);
    }
}