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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.config.properties.MinioProperties;
import com.cmvr.common.core.minio.MinioService;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.edge.client.service.EdgeHlcService;
import com.cmvr.llm.service.LLMTouchService;
import com.cmvr.test.enums.ActionEnum;
import com.cmvr.test.flow.context.TaskInstHolder;
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 LLMTouchOperateService implements LLMOperateService {

    private final TaskInstHolder taskInstHolder;
    private final MinioService minioService;
    private final MinioProperties minioProps;
    private final LLMTouchService llmTouchService;
    private final EdgeHlcService edgeHlcService;

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

    @Override
    public TaskNodeExecuteResult execute(TaskNodeExecuteMessage message) {
        ActionEnum action = message.getAction();
        JSONObject inputParams = message.getInputParams();
        String deviceId = inputParams.getString("deviceId");
        String terminalId = message.getTerminalId();

        JSONObject output = new JSONObject();
        switch (action) {
            case TOUCH_COORDINATES: {
                String targetFeature = inputParams.getString("targetFeature");
                String manufacturer = inputParams.getString("manufacturer");
                String vehType = inputParams.getString("vehType");
//                // 图片节点的id
//                FlowNodeWrapper imageNode = message.getGraph()
//                        .getNodeMap()
//                        .values()
//                        .stream()
//                        .filter(node -> ActionEnum.CAMERA_GETRGBIMAGE.equals(node.getAction()))
//                        .findFirst()
//                        .orElseThrow(() -> new IllegalStateException("未找到获取图片节点"));
//                JSONObject pre = taskInstHolder.getNodeOutParams(instId, imageNode.getNodeId());
//                JSONArray imageUrl = pre.getJSONArray("imageUrl");
//                String url = imageUrl.getString(imageUrl.size() - 1);

                // 直接从 inputParams 获取上游相机的输出（单个 imageUrl）
                String url = inputParams.getString("imageUrl");
                if (StrUtil.isEmpty(url)) {
                    throw new IllegalStateException("未找到上游相机输出的图片地址");
                }
                String bucketName = minioProps.getBucketName();
                String prefix = "/" + bucketName + "/";
                String objectName = StrUtil.removePrefix(url, StrUtil.subBefore(url, prefix, true) + prefix);
                try {
                    File image = minioService.getFile(bucketName, objectName);
                    output = llmTouchService.touchCoordinates(image, targetFeature, manufacturer, vehType);

                    // 计算坐标
                    JSONArray coords = output.getJSONArray("coordinates"); // [x1, y1, x2, y2]
                    int x1 = coords.getIntValue(0);
                    int y1 = coords.getIntValue(1);
                    int x2 = coords.getIntValue(2);
                    int y2 = coords.getIntValue(3);

                    int x = (x1 + x2) / 2;
                    int y = (y1 + y2) / 2;
                    String cal = StrUtil.format("{},{}", x, y);
                    output.put("coordinates", cal);

                    // todo 获取坐标后调用边缘系统
                    edgeHlcService.touch(image, terminalId, "hlc01", x, y, 100d);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                break;
            }

            default:
                throw new GlobalException("不支持的触控操作类型: " + action);
        }

        return TaskNodeExecuteResult.success(output);
    }
}