package top.tqx.demo_1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.tqx.demo_1.config.AiApiConfig;
import top.tqx.demo_1.dto.ReportResponse;
import top.tqx.demo_1.service.ReportService;
import top.tqx.demo_1.service.RagService;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private AiApiConfig aiApiConfig;

    @Autowired
    private RagService ragService;

    @Override
    public ReportResponse getWeeklyReport() throws IOException {
        String url = aiApiConfig.getFullUrl(aiApiConfig.getReports().getWeekly());
        log.info("调用RAG服务获取周报: url={}", url);

        try {
            String jsonResponse = ragService.getRequest(url, 30000);
            JsonNode rootNode = ragService.parseJson(jsonResponse);
            log.info("RAG服务获取周报成功");

            return parseReportResponse(rootNode);

        } catch (Exception e) {
            log.error("调用RAG服务获取周报失败: {}", e.getMessage(), e);
            return new ReportResponse();
        }
    }

    @Override
    public ReportResponse getMonthlyReport() throws IOException {
        String url = aiApiConfig.getFullUrl(aiApiConfig.getReports().getMonthly());
        log.info("调用RAG服务获取月报: url={}", url);

        try {
            String jsonResponse = ragService.getRequest(url, 30000);
            JsonNode rootNode = ragService.parseJson(jsonResponse);
            log.info("RAG服务获取月报成功");

            return parseReportResponse(rootNode);

        } catch (Exception e) {
            log.error("调用RAG服务获取月报失败: {}", e.getMessage(), e);
            return new ReportResponse();
        }
    }

    private ReportResponse parseReportResponse(JsonNode rootNode) {
        ReportResponse response = new ReportResponse();
        response.setSuccess(rootNode.has("success") ? rootNode.get("success").asBoolean() : false);

        if (rootNode.has("report") && rootNode.get("report").isObject()) {
            JsonNode reportNode = rootNode.get("report");
            ReportResponse.ReportData report = new ReportResponse.ReportData();

            if (reportNode.has("report_type")) {
                report.setReportType(reportNode.get("report_type").asText());
            }
            if (reportNode.has("start_date")) {
                report.setStartDate(reportNode.get("start_date").asText());
            }
            if (reportNode.has("end_date")) {
                report.setEndDate(reportNode.get("end_date").asText());
            }
            if (reportNode.has("total_queries")) {
                report.setTotalQueries(reportNode.get("total_queries").asInt());
            }
            if (reportNode.has("total_feedback")) {
                report.setTotalFeedback(reportNode.get("total_feedback").asInt());
            }
            if (reportNode.has("positive_count")) {
                report.setPositiveCount(reportNode.get("positive_count").asInt());
            }
            if (reportNode.has("negative_count")) {
                report.setNegativeCount(reportNode.get("negative_count").asInt());
            }
            if (reportNode.has("satisfaction_rate")) {
                report.setSatisfactionRate(new BigDecimal(reportNode.get("satisfaction_rate").asText()));
            }
            if (reportNode.has("avg_rating")) {
                report.setAvgRating(new BigDecimal(reportNode.get("avg_rating").asText()));
            }
            if (reportNode.has("created_at")) {
                report.setCreatedAt(reportNode.get("created_at").asText());
            }

            if (reportNode.has("high_freq_queries") && reportNode.get("high_freq_queries").isArray()) {
                List<ReportResponse.HighFreqQueryItem> highFreqQueries = new ArrayList<>();
                for (JsonNode queryNode : reportNode.get("high_freq_queries")) {
                    ReportResponse.HighFreqQueryItem item = new ReportResponse.HighFreqQueryItem();
                    if (queryNode.has("query")) {
                        item.setQuery(queryNode.get("query").asText());
                    }
                    if (queryNode.has("frequency")) {
                        item.setFrequency(queryNode.get("frequency").asInt());
                    }
                    if (queryNode.has("sample_answer")) {
                        item.setSampleAnswer(queryNode.get("sample_answer").asText());
                    }
                    highFreqQueries.add(item);
                }
                report.setHighFreqQueries(highFreqQueries);
            }

            if (reportNode.has("low_rating_queries") && reportNode.get("low_rating_queries").isArray()) {
                List<ReportResponse.LowRatingQueryItem> lowRatingQueries = new ArrayList<>();
                for (JsonNode queryNode : reportNode.get("low_rating_queries")) {
                    ReportResponse.LowRatingQueryItem item = new ReportResponse.LowRatingQueryItem();
                    if (queryNode.has("query")) {
                        item.setQuery(queryNode.get("query").asText());
                    }
                    if (queryNode.has("rating")) {
                        item.setRating(queryNode.get("rating").asInt());
                    }
                    if (queryNode.has("reason")) {
                        item.setReason(queryNode.get("reason").asText());
                    }
                    lowRatingQueries.add(item);
                }
                report.setLowRatingQueries(lowRatingQueries);
            }

            if (reportNode.has("improvement_suggestions") && reportNode.get("improvement_suggestions").isArray()) {
                List<String> suggestions = new ArrayList<>();
                for (JsonNode suggestionNode : reportNode.get("improvement_suggestions")) {
                    suggestions.add(suggestionNode.asText());
                }
                report.setImprovementSuggestions(suggestions);
            }

            response.setReport(report);
        }

        return response;
    }
}
