package tech.easyflow.publicapi.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import tech.easyflow.agent.runtime.AgentChatRequest;
import tech.easyflow.agent.runtime.AgentRunService;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.system.entity.SysApiKey;
import tech.easyflow.system.service.SysApiKeyService;

/**
 * Agent 公共调用接口。
 */
@RestController
@RequestMapping("/public-api/agent")
public class PublicAgentController {

    private final AgentRunService agentRunService;
    private final SysApiKeyService sysApiKeyService;

    /**
     * 创建 Agent 公共接口控制器。
     *
     * @param agentRunService Agent 运行服务
     * @param sysApiKeyService API Key 服务
     */
    public PublicAgentController(AgentRunService agentRunService,
                                 SysApiKeyService sysApiKeyService) {
        this.agentRunService = agentRunService;
        this.sysApiKeyService = sysApiKeyService;
    }

    /**
     * 通过 API Key 调用已发布 Agent。
     *
     * @param chatRequest Agent 聊天请求
     * @param request HTTP 请求
     * @return SSE Emitter
     */
    @PostMapping("/chat")
    public SseEmitter chat(@RequestBody AgentChatRequest chatRequest,
                           HttpServletRequest request) {
        String apiKey = request.getHeader(SysApiKey.KEY_Apikey);
        if (!StringUtils.hasText(apiKey)) {
            throw new BusinessException(401, 401, "Apikey不能为空!");
        }
        sysApiKeyService.checkApikeyPermission(apiKey, request.getRequestURI());
        SysApiKey sysApiKey = sysApiKeyService.getSysApiKey(apiKey);
        return agentRunService.chatPublic(chatRequest, buildApiAccount(sysApiKey));
    }

    /**
     * 将 API Key 转换为独立的聊天调用身份。
     *
     * @param sysApiKey API Key 记录
     * @return 调用身份
     */
    private LoginAccount buildApiAccount(SysApiKey sysApiKey) {
        LoginAccount account = new LoginAccount();
        account.setId(sysApiKey.getId());
        account.setTenantId(sysApiKey.getTenantId() == null
                ? java.math.BigInteger.ZERO
                : sysApiKey.getTenantId());
        account.setDeptId(sysApiKey.getDeptId() == null
                ? java.math.BigInteger.ZERO
                : sysApiKey.getDeptId());
        account.setLoginName("apikey:" + sysApiKey.getId());
        account.setNickname("API 调用方");
        return account;
    }
}
