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

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cool.modules.aiconfig.entity.AiApiConfigEntity;
import com.cool.modules.aiconfig.entity.AiModelEntity;
import com.cool.modules.aiconfig.entity.AiTemplateEntity;
import com.cool.modules.aiconfig.service.AiApiConfigService;
import com.cool.modules.aiconfig.service.AiModelService;
import com.cool.modules.aiconfig.service.AiTemplateService;
import com.cool.modules.monthlyreport.service.MonthlyReportAiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 月报AI格式化Service实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MonthlyReportAiServiceImpl implements MonthlyReportAiService {

    private final AiModelService aiModelService;
    private final AiApiConfigService aiApiConfigService;
    private final AiTemplateService aiTemplateService;

    @Override
    public String formatMonthlyReport(String originalText, String templateKey, String month) {
        String key = (templateKey == null || templateKey.isBlank()) ? "monthly_report_format" : templateKey;
        log.info("【月报AI格式化】开始格式化, templateKey={}, originalText长度={}, month={}",
            key, originalText != null ? originalText.length() : 0, month);

        try {
            AiTemplateEntity template = aiTemplateService.getByTemplateKey(key);
            if (template == null) {
                throw new RuntimeException("月报模板未配置: " + key);
            }

            AiModelEntity model = aiModelService.getById(template.getModelId());
            if (model == null) {
                throw new RuntimeException("AI模型未配置");
            }

            String prompt = buildPrompt(template.getPromptContent(), originalText, month);
            return callAiModel(model, prompt);
        } catch (Exception e) {
            log.error("【月报AI格式化】失败", e);
            throw new RuntimeException("AI格式化失败: " + e.getMessage(), e);
        }
    }

    private String buildPrompt(String templateContent, String originalText, String month) {
        String prompt = templateContent
            .replace("{original_text}", originalText)
            .replace("{{original_text}}", originalText)
            .replace("{content}", originalText)
            .replace("{{content}}", originalText);

        if (month != null && !month.isEmpty()) {
            prompt = prompt
                .replace("{month}", month)
                .replace("{{month}}", month);
        }
        return prompt;
    }

    private String callAiModel(AiModelEntity model, String prompt) {
        try {
            AiApiConfigEntity apiConfig = aiApiConfigService.getByModelId(model.getId());
            if (apiConfig == null) {
                throw new RuntimeException("AI模型API配置不存在");
            }

            JSONObject requestBody = new JSONObject();
            requestBody.set("model", model.getModelKey());

            JSONObject input = new JSONObject();
            JSONArray messages = new JSONArray();
            JSONObject message = new JSONObject();
            message.set("role", "user");
            message.set("content", prompt);
            messages.add(message);
            input.set("messages", messages);
            requestBody.set("input", input);

            JSONObject parameters = new JSONObject();
            parameters.set("max_tokens", 2000);
            requestBody.set("parameters", parameters);

            HttpRequest request = HttpRequest.post(apiConfig.getApiUrl())
                .header("Authorization", "Bearer " + apiConfig.getApiKey())
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .timeout(120000);

            HttpResponse response = request.execute();
            String responseBody = response.body();
            if (!response.isOk()) {
                throw new RuntimeException("AI模型调用失败: HTTP " + response.getStatus());
            }

            JSONObject result = JSONUtil.parseObj(responseBody);
            String content = result.getByPath("output.text", String.class);
            if (content == null || content.isEmpty()) {
                content = result.getByPath("output.choices[0].message.content", String.class);
            }
            if (content == null || content.isEmpty()) {
                throw new RuntimeException("AI模型返回内容为空");
            }
            return content;
        } catch (Exception e) {
            throw new RuntimeException("AI模型调用失败: " + e.getMessage(), e);
        }
    }
}
