package com.pavis.admin.aigc.core.agent.browser;

import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class ExecutionParam implements Serializable {

    private static final String EXECUTION_ENV_KEY_STRING = "current_step_env_data";

    private String planStatus;
    private Integer currentStepIndex;
    private String stepText;
    private String extraParams;
    private EnvData envData;
    private String envDataString;

    public Map<String, Object> getExecutionParamMap() {
        Map<String, Object> executionParamMap = new HashMap<>();
        executionParamMap.put("planStatus", planStatus);
        executionParamMap.put("currentStepIndex", currentStepIndex);
        executionParamMap.put("stepText", stepText);
        executionParamMap.put("extraParams", extraParams);
        executionParamMap.put(EXECUTION_ENV_KEY_STRING, envDataString);
        return executionParamMap;
    }

    /**
     * 获取环境字符串信息
     *
     * @return 环境字符串信息
     */
    public String getCurrentEnvString() {
        // 构建URL和标题信息
        String urlInfo = String.format("\n   URL: %s\n   Title: %s", envData.getUrl(), envData.getTitle());

        // 构建标签页信息
        List<Tab> tabs = envData.getTabs();
        String tabsInfo = (tabs != null) ? String.format("\n   %d tab(s) available", tabs.size()) : "";

        // 获取滚动信息
        ScrollInfo scrollInfo = envData.getScrollInfo();
        String contentAbove = "";
        String contentBelow = "";
        if (scrollInfo != null) {
            Long pixelsAbove = scrollInfo.getPixelsAbove();
            Long pixelsBelow = scrollInfo.getPixelsBelow();
            contentAbove = pixelsAbove > 0 ? String.format(" (%d pixels)", pixelsAbove) : "";
            contentBelow = pixelsBelow > 0 ? String.format(" (%d pixels)", pixelsBelow) : "";
        }

        // 获取交互元素信息
        String elementsInfo = envData.getInteractiveElements();

        // 构建最终的状态字符串
        String retString = String.format("""
            When you see [Current state starts here], focus on the following:
            - Current URL and page title:
            %s

            - Available tabs:
            %s

            - Interactive elements and their indices:
            %s

            - Content above%s or below%s the viewport (if indicated)

            - Any action results or errors:
            %s
            """, urlInfo, tabsInfo, elementsInfo != null ? elementsInfo : "", contentAbove, contentBelow, envData
            .getError());

        return retString;
    }
}
