package com.example.agentclient;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.agentclient.models.*;
import com.example.agentclient.utils.ApiClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主Activity - 调用情感分析Agent示例
 * 
 * 功能：
 * 1. 自动登录
 * 2. 通过Agent名称查找Agent ID
 * 3. 发送文本进行情感分析
 * 4. 轮询获取执行结果
 */
public class MainActivity extends AppCompatActivity {
    
    // TODO: 修改为你的配置
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "123456";
    private static final String AGENT_NAME = "情感分析Agent";  // Agent名称
    
    private TextView tvStatus;
    private TextView tvMessages;
    private EditText etInput;
    private Button btnSend;
    private ProgressBar progressBar;
    private ScrollView scrollView;
    
    private String accessToken;
    private String agentId;
    private Handler mainHandler;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 先初始化 Handler，因为 initViews() 中会使用它
        mainHandler = new Handler(Looper.getMainLooper());
        
        initViews();
        
        // 启动时自动登录
        login();
    }
    
    private void initViews() {
        tvStatus = findViewById(R.id.tvStatus);
        tvMessages = findViewById(R.id.tvMessages);
        etInput = findViewById(R.id.etInput);
        btnSend = findViewById(R.id.btnSend);
        progressBar = findViewById(R.id.progressBar);
        scrollView = findViewById(R.id.scrollView);
        
        btnSend.setOnClickListener(v -> {
            String input = etInput.getText().toString().trim();
            if (input.isEmpty()) {
                Toast.makeText(this, "请输入要分析的文本", Toast.LENGTH_SHORT).show();
                return;
            }
            sendMessage(input);
        });
        
        updateStatus("准备登录...");
        addMessage("系统", "正在连接服务器...");
    }
    
    /**
     * 登录
     */
    private void login() {
        updateStatus("正在登录...");
        addMessage("系统", "正在登录...");
        
        ApiClient.getService().login(USERNAME, PASSWORD).enqueue(new Callback<TokenResponse>() {
            @Override
            public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    accessToken = "Bearer " + response.body().getAccessToken();
                    updateStatus("登录成功");
                    addMessage("系统", "登录成功！正在查找Agent...");
                    
                    // 登录成功后查找Agent
                    findAgentByName(AGENT_NAME);
                } else {
                    String errorMsg = "登录失败: " + response.code();
                    try {
                        if (response.errorBody() != null) {
                            errorMsg += "\n" + response.errorBody().string();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    updateStatus("登录失败");
                    addMessage("系统", errorMsg);
                    Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                }
            }
            
            @Override
            public void onFailure(Call<TokenResponse> call, Throwable t) {
                String errorMsg = "登录失败: " + t.getMessage();
                updateStatus("登录失败");
                addMessage("系统", errorMsg);
                Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_LONG).show();
            }
        });
    }
    
    /**
     * 通过名称查找Agent
     */
    private void findAgentByName(String agentName) {
        updateStatus("正在查找Agent: " + agentName);
        
        ApiClient.getService().getAgents(agentName, 100, accessToken)
                .enqueue(new Callback<List<Agent>>() {
                    @Override
                    public void onResponse(Call<List<Agent>> call, Response<List<Agent>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            List<Agent> agents = response.body();
                            
                            // 精确匹配名称
                            Agent foundAgent = null;
                            for (Agent agent : agents) {
                                if (agentName.equals(agent.getName())) {
                                    foundAgent = agent;
                                    break;
                                }
                            }
                            
                            if (foundAgent != null) {
                                agentId = foundAgent.getId();
                                String status = foundAgent.getStatus();
                                updateStatus("已找到Agent: " + agentName);
                                addMessage("系统", String.format(
                                        "找到Agent: %s\nID: %s\n状态: %s",
                                        foundAgent.getName(),
                                        agentId,
                                        status
                                ));
                                
                                if (!"published".equals(status) && !"running".equals(status)) {
                                    addMessage("系统", "警告: Agent状态为 '" + status + "'，可能无法执行");
                                }
                                
                                addMessage("系统", "可以开始发送文本进行情感分析了！");
                            } else {
                                updateStatus("未找到Agent");
                                addMessage("系统", "未找到名称为 '" + agentName + "' 的Agent");
                                if (!agents.isEmpty()) {
                                    addMessage("系统", "找到以下相似的Agent:");
                                    for (int i = 0; i < Math.min(5, agents.size()); i++) {
                                        Agent agent = agents.get(i);
                                        addMessage("系统", String.format(
                                                "  - %s (ID: %s, 状态: %s)",
                                                agent.getName(),
                                                agent.getId(),
                                                agent.getStatus()
                                        ));
                                    }
                                }
                            }
                        } else {
                            String errorMsg = "查找Agent失败: " + response.code();
                            updateStatus("查找Agent失败");
                            addMessage("系统", errorMsg);
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<List<Agent>> call, Throwable t) {
                        String errorMsg = "查找Agent失败: " + t.getMessage();
                        updateStatus("查找Agent失败");
                        addMessage("系统", errorMsg);
                    }
                });
    }
    
    /**
     * 发送消息到Agent
     */
    private void sendMessage(String userInput) {
        if (agentId == null || agentId.isEmpty()) {
            Toast.makeText(this, "Agent未找到，请先查找Agent", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (accessToken == null || accessToken.isEmpty()) {
            Toast.makeText(this, "未登录，请先登录", Toast.LENGTH_SHORT).show();
            login();
            return;
        }
        
        // 禁用发送按钮
        btnSend.setEnabled(false);
        progressBar.setVisibility(View.VISIBLE);
        
        // 显示用户输入
        addMessage("我", userInput);
        updateStatus("正在发送请求...");
        
        // 构建请求数据
        Map<String, Object> inputData = new HashMap<>();
        inputData.put("query", userInput);
        inputData.put("USER_INPUT", userInput);
        
        AgentExecutionRequest request = new AgentExecutionRequest(agentId, inputData);
        
        // 执行Agent
        ApiClient.getService().executeAgent(request, accessToken)
                .enqueue(new Callback<ExecutionResponse>() {
                    @Override
                    public void onResponse(Call<ExecutionResponse> call, Response<ExecutionResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ExecutionResponse execution = response.body();
                            String executionId = execution.getId();
                            updateStatus("请求已发送，执行ID: " + executionId);
                            addMessage("系统", "正在处理，请稍候...");
                            
                            // 轮询获取结果
                            pollExecutionResult(executionId);
                        } else {
                            String errorMsg = "执行失败: " + response.code();
                            try {
                                if (response.errorBody() != null) {
                                    errorMsg += "\n" + response.errorBody().string();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            updateStatus("执行失败");
                            addMessage("系统", errorMsg);
                            btnSend.setEnabled(true);
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<ExecutionResponse> call, Throwable t) {
                        String errorMsg = "执行失败: " + t.getMessage();
                        updateStatus("执行失败");
                        addMessage("系统", errorMsg);
                        btnSend.setEnabled(true);
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }
    
    /**
     * 轮询获取执行结果
     */
    private void pollExecutionResult(String executionId) {
        ApiClient.getService().getExecutionStatus(executionId, accessToken)
                .enqueue(new Callback<ExecutionStatusResponse>() {
                    @Override
                    public void onResponse(Call<ExecutionStatusResponse> call, Response<ExecutionStatusResponse> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            ExecutionStatusResponse statusResponse = response.body();
                            String status = statusResponse.getStatus();
                            
                            // 显示当前节点信息
                            if (statusResponse.getCurrentNode() != null) {
                                ExecutionStatusResponse.CurrentNode node = statusResponse.getCurrentNode();
                                updateStatus(String.format("执行中: %s (%s)", 
                                        node.getNodeName() != null ? node.getNodeName() : node.getNodeId(),
                                        node.getNodeType()));
                            }
                            
                            if ("completed".equals(status)) {
                                // 执行完成，获取结果
                                getExecutionResult(executionId);
                            } else if ("failed".equals(status) || "error".equals(status)) {
                                // 执行失败
                                String errorMsg = statusResponse.getError();
                                if (errorMsg == null || errorMsg.isEmpty()) {
                                    errorMsg = "执行失败";
                                }
                                updateStatus("执行失败");
                                addMessage("系统", "执行失败: " + errorMsg);
                                btnSend.setEnabled(true);
                                progressBar.setVisibility(View.GONE);
                            } else {
                                // 继续轮询
                                mainHandler.postDelayed(() -> pollExecutionResult(executionId), 1000);
                            }
                        } else {
                            // 继续轮询
                            mainHandler.postDelayed(() -> pollExecutionResult(executionId), 1000);
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<ExecutionStatusResponse> call, Throwable t) {
                        // 继续轮询
                        mainHandler.postDelayed(() -> pollExecutionResult(executionId), 1000);
                    }
                });
    }
    
    /**
     * 获取执行结果
     */
    private void getExecutionResult(String executionId) {
        ApiClient.getService().getExecutionResult(executionId, accessToken)
                .enqueue(new Callback<ExecutionResponse>() {
                    @Override
                    public void onResponse(Call<ExecutionResponse> call, Response<ExecutionResponse> response) {
                        btnSend.setEnabled(true);
                        progressBar.setVisibility(View.GONE);
                        
                        if (response.isSuccessful() && response.body() != null) {
                            ExecutionResponse execution = response.body();
                            Object outputData = execution.getOutputData();
                            
                            updateStatus("执行完成");
                            
                            // 格式化输出
                            String result = formatOutput(outputData);
                            addMessage("Agent", result);
                        } else {
                            String errorMsg = "获取结果失败: " + response.code();
                            updateStatus("获取结果失败");
                            addMessage("系统", errorMsg);
                        }
                    }
                    
                    @Override
                    public void onFailure(Call<ExecutionResponse> call, Throwable t) {
                        btnSend.setEnabled(true);
                        progressBar.setVisibility(View.GONE);
                        String errorMsg = "获取结果失败: " + t.getMessage();
                        updateStatus("获取结果失败");
                        addMessage("系统", errorMsg);
                    }
                });
    }
    
    /**
     * 格式化输出数据
     */
    private String formatOutput(Object outputData) {
        if (outputData == null) {
            return "无输出";
        }
        
        if (outputData instanceof String) {
            return (String) outputData;
        }
        
        if (outputData instanceof Map) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) outputData;
            
            // 优先提取output字段
            if (map.containsKey("output") && map.get("output") instanceof String) {
                return (String) map.get("output");
            }
            
            // 如果只有一个key，直接返回其值
            if (map.size() == 1) {
                Object value = map.values().iterator().next();
                if (value instanceof String) {
                    return (String) value;
                }
            }
            
            // 否则转换为字符串
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (!entry.getKey().startsWith("_")) {
                    sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
                }
            }
            return sb.toString().trim();
        }
        
        return outputData.toString();
    }
    
    /**
     * 更新状态栏
     */
    private void updateStatus(String status) {
        if (mainHandler == null) {
            // 如果 Handler 还未初始化，直接在主线程更新
            if (tvStatus != null) {
                tvStatus.setText("状态: " + status);
            }
            return;
        }
        mainHandler.post(() -> {
            if (tvStatus != null) {
                tvStatus.setText("状态: " + status);
            }
        });
    }
    
    /**
     * 添加消息到消息列表
     */
    private void addMessage(String sender, String message) {
        if (mainHandler == null) {
            // 如果 Handler 还未初始化，直接在主线程更新
            if (tvMessages != null) {
                String newMessage = String.format("[%s] %s\n\n", sender, message);
                tvMessages.append(newMessage);
                
                // 自动滚动到底部
                if (scrollView != null) {
                    scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN));
                }
            }
            return;
        }
        mainHandler.post(() -> {
            if (tvMessages != null) {
                String currentText = tvMessages.getText().toString();
                String newMessage = String.format("[%s] %s\n\n", sender, message);
                tvMessages.append(newMessage);
                
                // 自动滚动到底部
                if (scrollView != null) {
                    scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN));
                }
            }
        });
    }
}
