package com.ruoyi.generator.service.front;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.config.DeepSeekProperties;

@Component
public class HttpDeepSeekClient implements IDeepSeekClient
{
    private static final HostnameVerifier TRUST_ALL_HOSTNAME_VERIFIER = new HostnameVerifier()
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            return true;
        }
    };

    private static final X509TrustManager TRUST_ALL_TRUST_MANAGER = new X509TrustManager()
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return new X509Certificate[0];
        }
    };

    private static final String SYSTEM_PROMPT = "你是企业管理系统数据库设计助手，只返回JSON。";

    @Autowired
    private DeepSeekProperties deepSeekProperties;

    @Override
    public String chat(String prompt)
    {
        if (StringUtils.isBlank(deepSeekProperties.getApiKey()))
        {
            throw new ServiceException("DeepSeek API Key 未配置");
        }
        JSONObject request = new JSONObject();
        request.put("model", deepSeekProperties.getModel());
        JSONArray messages = new JSONArray();
        messages.add(message("system", SYSTEM_PROMPT));
        messages.add(message("user", prompt));
        request.put("messages", messages);
        request.put("temperature", 0.2);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(deepSeekProperties.getApiKey());
        HttpEntity<String> entity = new HttpEntity<String>(request.toJSONString(), headers);
        ResponseEntity<String> response = restTemplate().postForEntity(chatUrl(), entity, String.class);
        return parseContent(response.getBody());
    }

    private JSONObject message(String role, String content)
    {
        JSONObject message = new JSONObject();
        message.put("role", role);
        message.put("content", content);
        return message;
    }

    private RestTemplate restTemplate()
    {
        int timeout = deepSeekProperties.getTimeout() == null ? 60000 : deepSeekProperties.getTimeout();
        return new RestTemplate(requestFactory(timeout));
    }

    SimpleClientHttpRequestFactory requestFactory(int timeout)
    {
        SimpleClientHttpRequestFactory factory = deepSeekProperties.isSkipSslVerify()
                ? trustAllRequestFactory()
                : new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(timeout);
        factory.setReadTimeout(timeout);
        return factory;
    }

    private SimpleClientHttpRequestFactory trustAllRequestFactory()
    {
        return new TrustAllClientHttpRequestFactory(trustAllSslContext());
    }

    private SSLContext trustAllSslContext()
    {
        try
        {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[] { TRUST_ALL_TRUST_MANAGER }, new SecureRandom());
            return sslContext;
        }
        catch (NoSuchAlgorithmException | KeyManagementException e)
        {
            throw new ServiceException("DeepSeek SSL 证书忽略配置初始化失败").setDetailMessage(e.getMessage());
        }
    }

    private static class TrustAllClientHttpRequestFactory extends SimpleClientHttpRequestFactory
    {
        private final SSLContext sslContext;

        private TrustAllClientHttpRequestFactory(SSLContext sslContext)
        {
            this.sslContext = sslContext;
        }

        @Override
        protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException
        {
            super.prepareConnection(connection, httpMethod);
            if (connection instanceof HttpsURLConnection)
            {
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
                httpsConnection.setHostnameVerifier(TRUST_ALL_HOSTNAME_VERIFIER);
            }
        }
    }

    private String chatUrl()
    {
        String baseUrl = StringUtils.defaultIfEmpty(deepSeekProperties.getBaseUrl(), "https://api.deepseek.com");
        return baseUrl.replaceAll("/+$", "") + "/chat/completions";
    }

    private String parseContent(String body)
    {
        JSONObject json = JSONObject.parseObject(body);
        JSONArray choices = json.getJSONArray("choices");
        if (choices == null || choices.isEmpty())
        {
            throw new ServiceException("DeepSeek 返回结果为空");
        }
        JSONObject message = choices.getJSONObject(0).getJSONObject("message");
        if (message == null || StringUtils.isBlank(message.getString("content")))
        {
            throw new ServiceException("DeepSeek 返回内容为空");
        }
        return message.getString("content");
    }
}
