package com.cool.modules.aiconfig.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cool.core.base.BaseServiceImpl;
import com.cool.core.exception.CoolPreconditions;
import com.cool.modules.aiconfig.entity.AiApiConfigEntity;
import com.cool.modules.aiconfig.mapper.AiApiConfigMapper;
import com.cool.modules.aiconfig.service.AiApiConfigService;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * AI模型接口配置服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiApiConfigServiceImpl extends BaseServiceImpl<AiApiConfigMapper, AiApiConfigEntity> implements AiApiConfigService {

    @Override
    public AiApiConfigEntity getByModelId(Long modelId) {
        log.info("【AI接口配置】根据模型ID获取接口配置, modelId: {}", modelId);

        CoolPreconditions.check(modelId == null, "模型ID不能为空");

        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq(AiApiConfigEntity::getModelId, modelId)
                .eq(AiApiConfigEntity::getStatus, 1);

        AiApiConfigEntity entity = this.getOne(queryWrapper);

        if (entity != null) {
            log.info("【AI接口配置】查询成功, configId: {}, apiUrl: {}", entity.getId(), entity.getApiUrl());
        } else {
            log.warn("【AI接口配置】未找到对应的接口配置, modelId: {}", modelId);
        }

        return entity;
    }

    @Override
    public boolean testConnection(Long id) {
        log.info("【AI接口配置】测试接口连通性, configId: {}", id);

        CoolPreconditions.check(id == null, "配置ID不能为空");

        AiApiConfigEntity config = this.getById(id);
        CoolPreconditions.check(config == null, "接口配置不存在");

        try {
            log.info("【AI接口配置】开始测试连接, apiUrl: {}", config.getApiUrl());

            // 构建HTTP请求
            HttpRequest request;
            if ("GET".equalsIgnoreCase(config.getRequestMethod())) {
                request = HttpRequest.get(config.getApiUrl());
            } else {
                request = HttpRequest.post(config.getApiUrl());
            }

            // 设置超时时间
            request.timeout(config.getTimeout() * 1000);

            // 设置请求头
            if (StrUtil.isNotEmpty(config.getRequestHeaders())) {
                JSONObject headers = JSONUtil.parseObj(config.getRequestHeaders());
                for (Map.Entry<String, Object> entry : headers.entrySet()) {
                    request.header(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }

            // 设置API密钥
            if (StrUtil.isNotEmpty(config.getApiKey()) && StrUtil.isNotEmpty(config.getApiKeyName())) {
                String apiKeyValue = config.getApiKey();
                // 如果API密钥名称是Authorization且密钥不以Bearer开头，自动添加Bearer前缀
                if ("Authorization".equalsIgnoreCase(config.getApiKeyName())
                    && !apiKeyValue.toLowerCase().startsWith("bearer ")) {
                    apiKeyValue = "Bearer " + apiKeyValue;
                }
                request.header(config.getApiKeyName(), apiKeyValue);
                log.info("【AI接口配置】设置API密钥, keyName: {}", config.getApiKeyName());
            }

            // POST请求需要发送测试请求体
            if ("POST".equalsIgnoreCase(config.getRequestMethod())) {
                // 构建一个简单的测试请求体（针对通义千问等大模型API）
                String testBody = "{\"model\":\"qwen-max\",\"input\":{\"messages\":[{\"role\":\"user\",\"content\":\"测试连接\"}]},\"parameters\":{\"max_tokens\":10}}";
                request.body(testBody);
                log.info("【AI接口配置】发送测试请求体: {}", testBody);
            }

            // 发送请求
            HttpResponse response = request.execute();
            String responseBody = response.body();

            log.info("【AI接口配置】测试完成, statusCode: {}, responseBody: {}",
                response.getStatus(), responseBody);

            // 判断是否成功：状态码2xx或响应体不包含明显的错误信息
            boolean isSuccess = response.isOk() ||
                (response.getStatus() >= 200 && response.getStatus() < 500 &&
                 StrUtil.isNotEmpty(responseBody) && !responseBody.contains("\"code\":\"InvalidApiKey\""));

            if (isSuccess) {
                log.info("【AI接口配置】接口连接测试成功");
            } else {
                log.warn("【AI接口配置】接口连接测试失败, statusCode: {}, body: {}",
                    response.getStatus(), responseBody);
            }

            return isSuccess;
        } catch (Exception e) {
            log.error("【AI接口配置】测试连接失败, error: {}", e.getMessage(), e);
            return false;
        }
    }
}
