/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.controller
 * @ClassName: OcrController
 * @Description: OCR控制器，提供OCR结果查询和管理接口
 * @Author: 张志锋
 * @Date: 2025-12-10
 * @Version: 1.0
 * @Copyright: 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.controller;

import com.zhpb.gdyd_zhpb_zgf.entity.mysql.OcrResult;
import com.zhpb.gdyd_zhpb_zgf.service.OcrService;
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.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * OCR控制器
 */
@RestController
@RequestMapping("/api/v1/files/ocr")
@Tag(name = "OCR管理", description = "OCR识别结果查询和管理接口")
public class OcrController {

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

    @Autowired
    private OcrService ocrService;

    /**
     * 根据文件ID获取OCR结果
     */
    @GetMapping("/file/{fileId}")
    @Operation(summary = "获取文件OCR结果", description = "根据文件ID获取OCR识别结果")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "204", description = "OCR结果不存在"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> getOcrResultByFileId(
            @Parameter(description = "文件ID") @PathVariable Long fileId) {

        try {
            Optional<OcrResult> ocrResult = ocrService.getOcrResultByFileId(fileId);

            if (ocrResult.isPresent()) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", ocrResult.get());
                return ResponseEntity.ok(result);
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 404);
                result.put("message", "OCR结果不存在");
                return ResponseEntity.status(404).body(result);
            }

        } catch (Exception e) {
            logger.error("查询OCR结果失败: fileId={}", fileId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据项目ID获取OCR结果列表
     */
    @GetMapping("/project/{projectId}")
    @Operation(summary = "获取项目OCR结果列表", description = "根据项目ID获取所有OCR识别结果")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> getOcrResultsByProject(
            @Parameter(description = "项目ID") @PathVariable String projectId,
            @Parameter(description = "供应商ID（可选）") @RequestParam(required = false) String supplierId) {

        try {
            List<OcrResult> ocrResults;
            if (supplierId != null && !supplierId.trim().isEmpty()) {
                ocrResults = ocrService.getOcrResultsByProjectAndSupplier(projectId, supplierId);
            } else {
                ocrResults = ocrService.getOcrResultsByProject(projectId);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", ocrResults);
            result.put("total", ocrResults.size());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("查询项目OCR结果失败: projectId={}, supplierId={}", projectId, supplierId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取项目OCR统计信息
     */
    @GetMapping("/project/{projectId}/stats")
    @Operation(summary = "获取项目OCR统计", description = "获取项目的OCR处理统计信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> getProjectOcrStatistics(
            @Parameter(description = "项目ID") @PathVariable String projectId) {

        try {
            Map<String, Object> stats = ocrService.getProjectOcrStatistics(projectId);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", stats);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("查询项目OCR统计失败: projectId={}", projectId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 重试失败的OCR任务
     */
    @PostMapping("/retry/{ocrResultId}")
    @Operation(summary = "重试OCR任务", description = "重试失败的OCR识别任务")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "重试任务已启动"),
        @ApiResponse(responseCode = "404", description = "OCR结果不存在"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> retryOcrTask(
            @Parameter(description = "OCR结果ID") @PathVariable Long ocrResultId) {

        try {
            // 这里可以先检查OCR结果是否存在和状态
            // 但为了简单，直接调用重试方法
            ocrService.retryFailedOcrTask(ocrResultId);

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "重试任务已启动");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("重试OCR任务失败: ocrResultId={}", ocrResultId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取失败的OCR任务列表
     */
    @GetMapping("/failed")
    @Operation(summary = "获取失败的OCR任务", description = "获取所有失败的OCR任务列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> getFailedOcrTasks() {

        try {
            List<OcrResult> failedTasks = ocrService.getFailedOcrTasks();

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", failedTasks);
            result.put("total", failedTasks.size());

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("查询失败的OCR任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
