package com.rj.service.biz.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rj.dto.CommunityFeedDTO;
import com.rj.dto.DifyWorkflowResponseDto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rj.entity.bz.CommunityFeedAnalysisResult;
import com.rj.service.DifyWorkflowService;
import com.rj.mapper.CommunityFeedAnalysisResultMapper;
import com.rj.service.biz.ICommunityFeedAnalysisResultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Map;
import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@Service
public class CommunityFeedAnalysisResultServiceImpl
        extends ServiceImpl<CommunityFeedAnalysisResultMapper, CommunityFeedAnalysisResult>
        implements ICommunityFeedAnalysisResultService {

    @Autowired
    private DifyWorkflowService difyWorkflowService;

    @Override
    public boolean saveResult(CommunityFeedAnalysisResult result) {
        try {
            log.info("保存社区Feed分析结果：{}", result);
            return this.save(result);
        } catch (Exception e) {
            log.error("保存社区Feed分析结果异常", e);
            return false;
        }
    }

    @Override
    public CommunityFeedAnalysisResult getByWorkflowId(String workflowId) {
        return this.getOne(new LambdaQueryWrapper<CommunityFeedAnalysisResult>()
                .eq(CommunityFeedAnalysisResult::getWorkflowId, workflowId)
                .last("limit 1"));
    }

    @Override
    public DifyWorkflowResponseDto callAiFeedWorkflow(CommunityFeedDTO requestDto) {
        Map<String, Object> inputs = new HashMap<>();
        inputs.put("targetContent", requestDto.getTargetContent());
        inputs.put("targetId", requestDto.getTargetId());
        inputs.put("targetType", requestDto.getTargetType());

        DifyWorkflowService.DifyWorkflowRequest request =
                new DifyWorkflowService.DifyWorkflowRequest(inputs, requestDto.getTargetId());

        DifyWorkflowService.DifyWorkflowResponse response =
                difyWorkflowService.callAiFeedWorkflow(request);

        try {
            JSONObject data = response.getData();
            if (data != null) {
                CommunityFeedAnalysisResult entity = new CommunityFeedAnalysisResult();

                // 顶层通用信息
                entity.setWorkflowId(data.getString("workflow_id"));
                entity.setStatus(data.getString("status"));
                entity.setTotalTokens(data.getInteger("total_tokens"));
                if (data.containsKey("elapsed_time")) {
                    try {
                        entity.setElapsedTime(data.getBigDecimal("elapsed_time"));
                    } catch (Exception ex) {
                        try {
                            entity.setElapsedTime(new BigDecimal(String.valueOf(data.get("elapsed_time"))));
                        } catch (Exception ig) {
                            log.warn("elapsed_time 解析失败: {}", data.get("elapsed_time"));
                        }
                    }
                }
                entity.setError(data.getString("error"));

                // 解析 outputs.feedAiResult（可能是 ```json 包裹的字符串）
                JSONObject outputs = data.getJSONObject("outputs");
                if (outputs != null && outputs.containsKey("feedAiResult")) {
                    String feedAiResult = outputs.getString("feedAiResult");
                    if (feedAiResult != null) {
                        // 清理 ```json 代码块
                        String cleaned = feedAiResult.trim();
                        if (cleaned.startsWith("```json")) {
                            cleaned = cleaned.substring(7).trim();
                        } else if (cleaned.startsWith("```")) {
                            cleaned = cleaned.substring(3).trim();
                        }
                        if (cleaned.endsWith("```")) {
                            cleaned = cleaned.substring(0, cleaned.length() - 3).trim();
                        }
                        try {
                            JSONObject scoreJson = JSON.parseObject(cleaned);
                            entity.setLengthScore(scoreJson.getInteger("length"));
                            entity.setImageScore(scoreJson.getInteger("image"));
                            entity.setTopicsScore(scoreJson.getInteger("topics"));
                            entity.setEmotionScore(scoreJson.getInteger("emotion"));
                            entity.setThemeScore(scoreJson.getInteger("theme"));
                            entity.setFluencyScore(scoreJson.getInteger("fluency"));
                            entity.setContentScore(scoreJson.getInteger("contentScore"));
                            entity.setEvaluationReason(scoreJson.getString("evaluationReason"));
                        } catch (Exception ignore) {
                            log.warn("解析feedAiResult为JSON失败，cleaned: {}", cleaned);
                        }
                    }
                }

                // 源内容：从请求与 outputs 回填
                entity.setSrcContent(requestDto.getTargetContent());
                if (outputs != null) {
                    entity.setSrcId(outputs.getString("targetId"));
                    entity.setSrcType(outputs.getString("targetType"));
                }

                // 时间字段
                LocalDateTime now = LocalDateTime.now();
                entity.setCreatedAt(now);
                entity.setUpdatedAt(now);

                boolean saved = this.save(entity);
                log.info("AI-Feed分析结果保存{}: {}", saved ? "成功" : "失败", entity);
            }
        } catch (Exception e) {
            log.error("保存AI-Feed分析结果到DB失败", e);
        }

        return DifyWorkflowResponseDto.success(
                response.getWorkflowRunId(),
                response.getTaskId(),
                response.getData(),
                response.getMetadata()
        );
    }
}


