package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.entity.ChatMessage;
import top.tqx.demo_1.entity.Feedback;
import top.tqx.demo_1.mapper.ChatMessageMapper;
import top.tqx.demo_1.mapper.ChatSessionMapper;
import top.tqx.demo_1.mapper.FeedbackMapper;
import top.tqx.demo_1.entity.ChatSession;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "AI数据接口", description = "专门为AI端提供的数据查询接口")
@RestController
@RequestMapping("/ai/data")
@Slf4j
public class AiDataController {

    @Autowired
    private ChatSessionMapper chatSessionMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Operation(summary = "获取会话历史消息", description = "AI端通过session_id获取完整的对话历史")
    @GetMapping("/session/{sessionId}/messages")
    public Result<List<ChatMessage>> getSessionMessages(
            @Parameter(description = "会话ID") @PathVariable String sessionId) {
        try {
            log.info("AI端获取会话历史: sessionId={}", sessionId);

            ChatSession session = chatSessionMapper.selectOne(
                    new LambdaQueryWrapper<ChatSession>()
                            .eq(ChatSession::getSessionId, sessionId)
            );

            if (session == null) {
                log.warn("会话不存在: sessionId={}", sessionId);
                return Result.error("会话不存在");
            }

            List<ChatMessage> messages = chatMessageMapper.selectList(
                    new LambdaQueryWrapper<ChatMessage>()
                            .eq(ChatMessage::getConversationId, session.getId())
                            .orderByAsc(ChatMessage::getCreateTime)
            );

            log.info("获取会话消息成功: sessionId={}, count={}", sessionId, messages.size());
            return Result.success(messages);
        } catch (Exception e) {
            log.error("获取会话历史失败: sessionId={}, error={}", sessionId, e.getMessage(), e);
            return Result.error("获取会话历史失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取用户反馈列表", description = "AI端获取所有反馈数据用于分析")
    @GetMapping("/feedbacks")
    public Result<List<Feedback>> getFeedbacks(
            @Parameter(description = "评分筛选：1=好评，-1=差评") @RequestParam(required = false) Integer rating) {
        try {
            log.info("AI端获取反馈列表: rating={}", rating);

            LambdaQueryWrapper<Feedback> wrapper = new LambdaQueryWrapper<>();
            if (rating != null) {
                wrapper.eq(Feedback::getRating, rating);
            }
            wrapper.orderByDesc(Feedback::getCreatedAt);

            List<Feedback> feedbacks = feedbackMapper.selectList(wrapper);

            log.info("获取反馈列表成功: count={}", feedbacks.size());
            return Result.success(feedbacks);
        } catch (Exception e) {
            log.error("获取反馈列表失败: error={}", e.getMessage(), e);
            return Result.error("获取反馈列表失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取差评案例", description = "AI端获取差评案例用于分析改进")
    @GetMapping("/feedbacks/bad-cases")
    public Result<List<Feedback>> getBadCases() {
        try {
            log.info("AI端获取差评案例");

            List<Feedback> badCases = feedbackMapper.selectList(
                    new LambdaQueryWrapper<Feedback>()
                            .eq(Feedback::getRating, -1)
                            .orderByDesc(Feedback::getCreatedAt)
            );

            log.info("获取差评案例成功: count={}", badCases.size());
            return Result.success(badCases);
        } catch (Exception e) {
            log.error("获取差评案例失败: error={}", e.getMessage(), e);
            return Result.error("获取差评案例失败: " + e.getMessage());
        }
    }
}