package com.cool.modules.weeklyreport.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.weeklyreport.service.WeeklyReportAiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 周报AI格式化Service实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WeeklyReportAiServiceImpl implements WeeklyReportAiService {

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

    @Override
    public String formatWeeklyReport(String originalText, String templateKey, String weekStartDate, String weekEndDate) {
        log.info("【周报AI格式化】开始格式化周报, templateKey={}, originalText长度={}, weekStartDate={}, weekEndDate={}",
            templateKey, originalText != null ? originalText.length() : 0, weekStartDate, weekEndDate);

        try {
            // 1. 获取AI模板
            AiTemplateEntity template = aiTemplateService.getByTemplateKey(templateKey);
            if (template == null) {
                log.error("【周报AI格式化】模板未配置, templateKey={}", templateKey);
                throw new RuntimeException("周报模板未配置，请联系管理员");
            }

            log.info("【周报AI格式化】获取模板成功, templateName={}, modelId={}",
                template.getTemplateName(), template.getModelId());

            // 2. 获取AI模型配置
            AiModelEntity model = aiModelService.getById(template.getModelId());
            if (model == null) {
                log.error("【周报AI格式化】AI模型未配置, modelId={}", template.getModelId());
                throw new RuntimeException("AI模型未配置");
            }

            log.info("【周报AI格式化】获取AI模型成功, modelName={}, modelKey={}",
                model.getModelName(), model.getModelKey());

            // 3. 构建提示词（替换模板中的占位符）
            String prompt = buildPrompt(template.getPromptContent(), originalText, weekStartDate, weekEndDate);
            log.info("【周报AI格式化】构建提示词成功, prompt长度={}", prompt.length());

            // 4. 调用AI模型生成内容
            String formattedContent = callAiModel(model, prompt);
            log.info("【周报AI格式化】AI生成成功, 生成内容长度={}", formattedContent.length());

            return formattedContent;
        } catch (Exception e) {
            log.error("【周报AI格式化】格式化失败", e);
            throw new RuntimeException("AI格式化失败: " + e.getMessage(), e);
        }
    }

    /**
     * 构建提示词，替换模板中的占位符
     */
    private String buildPrompt(String templateContent, String originalText, String weekStartDate, String weekEndDate) {
        log.info("【周报AI格式化】开始构建提示词");

        String prompt = templateContent
            // 支持多种内容占位符格式
            .replace("{original_text}", originalText)
            .replace("{{original_text}}", originalText)
            .replace("{content}", originalText)
            .replace("{{content}}", originalText);

        // 替换周开始日期
        if (weekStartDate != null && !weekStartDate.isEmpty()) {
            prompt = prompt
                .replace("{week_start_date}", weekStartDate)
                .replace("{{week_start_date}}", weekStartDate)
                .replace("{start_date}", weekStartDate)
                .replace("{{start_date}}", weekStartDate);
        }

        // 替换周结束日期
        if (weekEndDate != null && !weekEndDate.isEmpty()) {
            prompt = prompt
                .replace("{week_end_date}", weekEndDate)
                .replace("{{week_end_date}}", weekEndDate)
                .replace("{end_date}", weekEndDate)
                .replace("{{end_date}}", weekEndDate);
        }

        // 替换周范围（格式：2023-11-06 至 2023-11-12）
        if (weekStartDate != null && weekEndDate != null) {
            String weekRange = weekStartDate + " 至 " + weekEndDate;
            prompt = prompt
                .replace("{week_range}", weekRange)
                .replace("{{week_range}}", weekRange);
        }

        log.info("【周报AI格式化】提示词构建完成");
        return prompt;
    }

    /**
     * 调用AI模型生成内容
     */
    private String callAiModel(AiModelEntity model, String prompt) {
        log.info("【周报AI格式化】开始调用AI模型, modelKey={}", model.getModelKey());

        try {
            // 获取API配置
            AiApiConfigEntity apiConfig = aiApiConfigService.getByModelId(model.getId());
            if (apiConfig == null) {
                log.error("【周报AI格式化】API配置不存在, modelId={}", model.getId());
                throw new RuntimeException("AI模型API配置不存在");
            }

            log.info("【周报AI格式化】获取API配置成功, apiUrl={}", apiConfig.getApiUrl());

            // 构建请求体（通义千问格式）
            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);

            log.info("【周报AI格式化】发送AI请求, requestBody={}", requestBody.toString());

            // 发送HTTP请求
            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();

            log.info("【周报AI格式化】收到AI响应, status={}, responseBody={}",
                response.getStatus(), responseBody);

            if (!response.isOk()) {
                log.error("【周报AI格式化】AI请求失败, status={}, body={}",
                    response.getStatus(), responseBody);
                throw new RuntimeException("AI模型调用失败: HTTP " + response.getStatus());
            }

            // 解析响应
            JSONObject result = JSONUtil.parseObj(responseBody);

            // 尝试从 output.text 获取内容
            String content = result.getByPath("output.text", String.class);

            // 如果没有，尝试从 output.choices[0].message.content 获取
            if (content == null || content.isEmpty()) {
                content = result.getByPath("output.choices[0].message.content", String.class);
            }

            if (content == null || content.isEmpty()) {
                log.error("【周报AI格式化】AI响应中未找到生成内容, response={}", responseBody);
                throw new RuntimeException("AI模型返回内容为空");
            }

            log.info("【周报AI格式化】AI调用成功, 生成内容长度={}", content.length());
            return content;
        } catch (Exception e) {
            log.error("【周报AI格式化】AI模型调用失败", e);
            throw new RuntimeException("AI模型调用失败: " + e.getMessage(), e);
        }
    }
}
