package com.gxwebsoft.house.ai;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * 通义千问兼容接口实现，凭据从应用配置读取。
 */
@Component
public class QwenHouseAiModelClient implements HouseAiModelClient {

    @Value("${house.ai.model.endpoint}")
    private String endpoint;

    @Value("${house.ai.model.name}")
    private String modelName;

    @Value("${house.ai.model.api-key}")
    private String apiKey;

    @Override
    public String complete(JSONArray messages) {
        if (StrUtil.isBlank(endpoint) || StrUtil.isBlank(modelName)) {
            throw new IllegalStateException("未配置找房智能体模型服务地址或模型名称");
        }
        if (StrUtil.isBlank(apiKey)) {
            throw new IllegalStateException("未配置找房智能体模型密钥");
        }
        HttpURLConnection connection = null;
        try {
            JSONObject request = new JSONObject();
            request.put("model", modelName);
            request.put("messages", messages);
            request.put("temperature", 0.2);
            request.put("stream", false);

            connection = (HttpURLConnection) new URL(endpoint).openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setConnectTimeout(20000);
            connection.setReadTimeout(20000);
            connection.setDoOutput(true);
            try (OutputStream output = connection.getOutputStream()) {
                output.write(request.toJSONString().getBytes(StandardCharsets.UTF_8));
            }

            int status = connection.getResponseCode();
            InputStream stream = status >= 400 ? connection.getErrorStream() : connection.getInputStream();
            if (stream == null) {
                throw new IllegalStateException("模型服务未返回内容");
            }
            StringBuilder body = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    body.append(line);
                }
            }
            if (status >= 400) {
                throw new IllegalStateException("模型服务请求失败");
            }
            JSONObject response = JSONObject.parseObject(body.toString());
            JSONArray choices = response == null ? null : response.getJSONArray("choices");
            if (choices == null || choices.isEmpty()) {
                throw new IllegalStateException("模型服务未返回有效回复");
            }
            JSONObject message = choices.getJSONObject(0).getJSONObject("message");
            String content = message == null ? null : message.getString("content");
            if (StrUtil.isBlank(content)) {
                throw new IllegalStateException("模型服务回复为空");
            }
            return content;
        } catch (Exception e) {
            throw new IllegalStateException("调用找房智能体模型失败", e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
