package cn.com.poc.expose.rest.impl;

import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.StringUtils;
import cn.com.poc.expose.aggregate.AgentApplicationApiService;
import cn.com.poc.expose.dto.model_link_api.CompletionsDto;
import cn.com.poc.expose.dto.model_link_api.CreateConversationDto;
import cn.com.poc.expose.rest.ModelLinkRest;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author alex.yao
 * @date 2024/12/23
 */
@Component
public class ModelLinkRestImpl implements ModelLinkRest {

    @Resource
    private AgentApplicationApiService agentApplicationApiService;


    @Override
    public String conversation(CreateConversationDto dto, HttpServletRequest httpServletRequest) throws Exception {
        Assert.notBlank(dto.getAgentId(), "Agent Id Can't Null");
        String apiKey = httpServletRequest.getHeader("x-api-key");
        String apiSecret = httpServletRequest.getHeader("x-api-secret");
        checkApiKeyAndSecret(httpServletRequest);
        return agentApplicationApiService.conversation(apiKey, apiSecret, dto.getAgentId());
    }

    @Override
    public void completions(CompletionsDto dto, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        String apiKey = httpServletRequest.getHeader("x-api-key");
        String apiSecret = httpServletRequest.getHeader("x-api-secret");
        checkApiKeyAndSecret(httpServletRequest);
        List<String> fileIds = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getFileId())) {
            fileIds.add(dto.getFileId());
        }
        agentApplicationApiService.completions(apiKey, apiSecret, dto.getConversationId(), fileIds, dto.getQuery(), dto.getStream(), httpServletResponse);
    }

    @Override
    public String uploadFile(String agentId, String conversationId, MultipartFile file, HttpServletRequest httpServletRequest) throws Exception {
        String apiKey = httpServletRequest.getHeader("x-api-key");
        String apiSecret = httpServletRequest.getHeader("x-api-secret");
        checkApiKeyAndSecret(httpServletRequest);
        return agentApplicationApiService.uploadFile(apiKey, apiSecret, agentId, conversationId, file);
    }

    private void checkApiKeyAndSecret(HttpServletRequest httpServletRequest) {
        String apiKey = httpServletRequest.getHeader("x-api-key");
        String apiSecret = httpServletRequest.getHeader("x-api-secret");
        if (StringUtils.isBlank(apiKey) || StringUtils.isBlank(apiSecret)) {
            throw new BusinessException("Api Key And Api Secret Can't Null");
        }
    }
}
