/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.controller
 * @ClassName: QaController
 * @Description: 智能问答控制器
 * @Author: 张志锋
 * @Date: 2025-11-03
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.controller;

import com.zhpb.gdyd_zhpb_zgf.dto.QaHistoryResponse;
import com.zhpb.gdyd_zhpb_zgf.dto.QaRequest;
import com.zhpb.gdyd_zhpb_zgf.dto.QaResponse;
import com.zhpb.gdyd_zhpb_zgf.service.QaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import com.zhpb.gdyd_zhpb_zgf.service.UserLogService;

/**
 * 智能问答控制器
 */
@RestController
@RequestMapping("/api/v1/qa")
@Tag(name = "智能问答", description = "基于文档的智能问答接口")
public class QaController {

    private static final Logger logger = LoggerFactory.getLogger(QaController.class);

    @Autowired
    private QaService qaService;
    
    @Autowired
    private UserLogService userLogService;

    @PostMapping("/sendMessage")
    @Operation(summary = "发送对话消息", description = "用户输入问题，针对一个或多个文件进行提问")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "Successful Response"),
            @ApiResponse(responseCode = "422", description = "Validation Error")
    })
    public ResponseEntity<QaResponse> sendMessage(
            @Parameter(description = "智能问答请求")
            @RequestBody @Validated QaRequest request) {

        logger.info("收到智能问答请求: projectId={}, userId={}, query={}",
                request.getProjectId(), request.getUserId(), request.getQuery());

        try {
            QaResponse.QaData data = qaService.sendMessage(request);

            QaResponse response = new QaResponse();
            response.setCode(0);
            response.setMessage("查询成功");
            response.setData(data);

            // 记录用户操作日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest httpRequest = attributes.getRequest();
            userLogService.logUserOperation(request.getUserId(), null, request.getProjectId(), 
                "QA_QUESTION", "发送问答消息: " + request.getQuery(), null, httpRequest);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("智能问答处理失败", e);
            QaResponse response = new QaResponse();
            response.setCode(500);
            response.setMessage("系统错误: " + e.getMessage());
            response.setData(new QaResponse.QaData());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @GetMapping("/history/sessions")
    @Operation(summary = "查询历史会话", description = "根据项目ID和用户ID查询历史会话列表")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<QaHistoryResponse> getSessionHistory(
            @Parameter(description = "项目ID", required = true)
            @RequestParam String projectId,
            @Parameter(description = "用户ID", required = true)
            @RequestParam String userId,
            @Parameter(description = "用户名", required = false)
            @RequestParam(required = false) String userName,
            @Parameter(description = "用户名（兼容字段）", required = false)
            @RequestParam(value = "user_name", required = false) String legacyUserName) {

        logger.info("查询历史会话: projectId={}, userId={}", projectId, userId);

        try {
            QaHistoryResponse.SessionsData data = qaService.getSessionHistory(projectId, userId);

            QaHistoryResponse response = new QaHistoryResponse();
            response.setCode(0);
            response.setMessage("Success");
            response.setData(data);

            // 记录用户操作日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest httpRequest = attributes.getRequest();
            String resolvedUserName = StringUtils.hasText(userName) ? userName : legacyUserName;
            if (!StringUtils.hasText(resolvedUserName) && httpRequest != null) {
                resolvedUserName = httpRequest.getHeader("User-Name");
                if (!StringUtils.hasText(resolvedUserName)) {
                    resolvedUserName = httpRequest.getHeader("userName");
                }
            }
            userLogService.logUserOperation(userId, resolvedUserName, projectId, 
                "VIEW_QA_SESSIONS", "查询历史会话", null, httpRequest);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("查询历史会话失败", e);
            QaHistoryResponse response = new QaHistoryResponse();
            response.setCode(500);
            response.setMessage("系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @GetMapping("/history/messages")
    @Operation(summary = "查询会话消息历史", description = "根据会话ID查询消息历史")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "会话不存在"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<QaHistoryResponse> getMessageHistory(
            @Parameter(description = "会话ID", required = true)
            @RequestParam String sessionId) {

        logger.info("查询会话消息历史: sessionId={}", sessionId);

        try {
            QaHistoryResponse.MessagesData data = qaService.getMessageHistory(sessionId);

            if (data.getMessages().isEmpty()) {
                QaHistoryResponse response = new QaHistoryResponse();
                response.setCode(200);
                response.setMessage("会话不存在或无消息记录");
                return ResponseEntity.ok().body(response);
            }

            QaHistoryResponse response = new QaHistoryResponse();
            response.setCode(0);
            response.setMessage("Success");
            response.setData(data);

            // 记录用户操作日志
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest httpRequest = attributes.getRequest();
            userLogService.logUserOperation(null, null, null, 
                "VIEW_QA_MESSAGES", "查看问答历史消息", sessionId, httpRequest);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("查询会话消息历史失败", e);
            QaHistoryResponse response = new QaHistoryResponse();
            response.setCode(500);
            response.setMessage("系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
