package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
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.dto.*;
import top.tqx.demo_1.service.UserAnswerService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Tag(name = "错题管理", description = "错题查看、收藏、重练、导出接口")
@RestController
@RequestMapping("/wrong-questions")
@Slf4j
public class WrongQuestionController extends BaseController {

    @Autowired
    private UserAnswerService userAnswerService;

    @Operation(summary = "获取错题列表", description = "分页获取用户错题列表，支持按题型、收藏状态、时间范围、知识库筛选")
    @PostMapping("/list")
    public Result<WrongQuestionListResponse> getWrongQuestions(
            @RequestBody WrongQuestionListRequest request,
            HttpServletRequest httpRequest) {

        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            return Result.error(401, "用户未登录");
        }

        if (request.getPage() == null || request.getPage() < 1) {
            request.setPage(1);
        }
        if (request.getPageSize() == null || request.getPageSize() < 1 || request.getPageSize() > 100) {
            request.setPageSize(20);
        }

        log.info("获取错题列表: userId={}, questionType={}, isCollected={}",
                userId, request.getQuestionType(), request.getIsCollected());

        try {
            WrongQuestionListResponse response = userAnswerService.getWrongQuestions(userId, request);
            return Result.success("获取错题列表成功", response);
        } catch (Exception e) {
            log.error("获取错题列表异常: {}", e.getMessage(), e);
            return Result.error(500, "获取错题列表异常: " + e.getMessage());
        }
    }

    @Operation(summary = "获取收藏的错题列表", description = "获取用户收藏的所有错题，支持分页")
    @PostMapping("/collection/list")
    public Result<WrongQuestionListResponse> getCollectedWrongQuestions(
            @RequestBody WrongQuestionListRequest request,
            HttpServletRequest httpRequest) {

        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            return Result.error(401, "用户未登录");
        }

        // 强制设置为已收藏状态
        request.setIsCollected(true);

        if (request.getPage() == null || request.getPage() < 1) {
            request.setPage(1);
        }
        if (request.getPageSize() == null || request.getPageSize() < 1 || request.getPageSize() > 100) {
            request.setPageSize(20);
        }

        log.info("获取收藏错题列表: userId={}, page={}, pageSize={}",
                userId, request.getPage(), request.getPageSize());

        try {
            WrongQuestionListResponse response = userAnswerService.getWrongQuestions(userId, request);
            return Result.success("获取收藏错题列表成功", response);
        } catch (Exception e) {
            log.error("获取收藏错题列表异常: {}", e.getMessage(), e);
            return Result.error(500, "获取收藏错题列表异常: " + e.getMessage());
        }
    }

    @Operation(summary = "检查题目是否已收藏", description = "检查指定题目是否已被当前用户收藏")
    @GetMapping("/collection/check")
    public Result<Boolean> checkCollectionStatus(
            @RequestParam("question_id") String questionId,
            HttpServletRequest httpRequest) {

        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            return Result.error(401, "用户未登录");
        }

        if (questionId == null || questionId.isEmpty()) {
            return Result.error(400, "questionId不能为空");
        }

        log.info("检查收藏状态: userId={}, questionId={}", userId, questionId);

        try {
            boolean isCollected = userAnswerService.checkQuestionCollected(userId, questionId);
            return Result.success(isCollected);
        } catch (Exception e) {
            log.error("检查收藏状态异常: {}", e.getMessage(), e);
            return Result.error(500, "检查收藏状态异常: " + e.getMessage());
        }
    }

    @Operation(summary = "收藏/取消收藏错题", description = "收藏或取消收藏指定的错题，支持添加备注")
    @PostMapping("/collection/toggle")
    public Result<Void> toggleCollection(
            @RequestBody WrongQuestionCollectRequest request,
            HttpServletRequest httpRequest) {

        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            return Result.error(401, "用户未登录");
        }

        if (request.getAnswerId() == null && request.getQuestionId() == null) {
            return Result.error(400, "answerId或questionId不能为空");
        }
        if (request.getIsCollected() == null) {
            return Result.error(400, "isCollected不能为空");
        }

        log.info("收藏错题: userId={}, answerId={}, questionId={}, isCollected={}",
                userId, request.getAnswerId(), request.getQuestionId(), request.getIsCollected());

        try {
            boolean success = userAnswerService.toggleWrongQuestionCollection(userId, request);
            if (success) {
                return Result.success("操作成功", null);
            } else {
                return Result.error(500, "操作失败");
            }
        } catch (Exception e) {
            log.error("收藏错题异常: {}", e.getMessage(), e);
            return Result.error(500, "收藏错题异常: " + e.getMessage());
        }
    }

    @Operation(summary = "生成错题重练试卷", description = "根据错题生成重练试卷，支持按题型、收藏状态筛选")
    @PostMapping("/redo")
    public Result<ExamPaperGenerateResponse> redoWrongQuestions(
            @RequestBody WrongQuestionRedoRequest request,
            HttpServletRequest httpRequest) {

        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            return Result.error(401, "用户未登录");
        }

        if (request.getQuestionCount() == null || request.getQuestionCount() < 1) {
            request.setQuestionCount(10);
        }
        if (request.getQuestionCount() > 100) {
            request.setQuestionCount(100);
        }

        log.info("生成错题重练试卷: userId={}, questionCount={}, questionType={}",
                userId, request.getQuestionCount(), request.getQuestionType());

        try {
            ExamPaperGenerateResponse response = userAnswerService.redoWrongQuestions(userId, request);
            return Result.success("生成试卷成功", response);
        } catch (Exception e) {
            log.error("生成错题重练试卷异常: {}", e.getMessage(), e);
            return Result.error(500, "生成试卷异常: " + e.getMessage());
        }
    }

    @Operation(summary = "导出错题", description = "导出用户错题为CSV格式")
    @PostMapping("/export")
    public void exportWrongQuestions(
            @RequestBody WrongQuestionListRequest request,
            HttpServletRequest httpRequest,
            HttpServletResponse response) {

        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            response.setStatus(401);
            return;
        }

        log.info("导出错题: userId={}", userId);

        try {
            List<WrongQuestionListResponse.WrongQuestionItem> items =
                    userAnswerService.exportWrongQuestions(userId, request);

            response.setContentType("text/csv;charset=UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename=wrong-questions-" + System.currentTimeMillis() + ".csv");

            PrintWriter writer = response.getWriter();
            writer.println("ID,题型,题目内容,用户答案,正确答案,得分,满分,难度,文档,错题次数,回答时间");

            for (WrongQuestionListResponse.WrongQuestionItem item : items) {
                writer.printf("%d,%s,\"%s\",\"%s\",\"%s\",%s,%s,%d,\"%s\",%d,%s%n",
                        item.getAnswerId(),
                        item.getQuestionTypeName(),
                        escapeCsv(item.getQuestionContent() != null ? item.getQuestionContent().toString() : ""),
                        escapeCsv(item.getUserAnswer() != null ? item.getUserAnswer().toString() : ""),
                        escapeCsv(item.getCorrectAnswer() != null ? item.getCorrectAnswer().toString() : ""),
                        item.getScore() != null ? item.getScore().toString() : "0",
                        item.getMaxScore() != null ? item.getMaxScore().toString() : "0",
                        item.getDifficulty() != null ? item.getDifficulty() : 3,
                        escapeCsv(item.getDocumentName() != null ? item.getDocumentName() : ""),
                        item.getWrongCount() != null ? item.getWrongCount() : 1,
                        item.getAnsweredAt() != null ? item.getAnsweredAt().toString() : ""
                );
            }

            writer.flush();
        } catch (Exception e) {
            log.error("导出错题异常: {}", e.getMessage(), e);
            try {
                response.sendError(500, "导出异常: " + e.getMessage());
            } catch (IOException ex) {
                log.error("发送错误响应异常: {}", ex.getMessage());
            }
        }
    }

    private String escapeCsv(String value) {
        if (value == null) {
            return "";
        }
        if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }
        return value;
    }
}
