package com.lingyue.parse.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.parse.service.ParseTaskCenterService;
import com.lingyue.parse.service.ParseTaskExecutor;
import com.lingyue.parse.service.WordStructuredExtractionService;
import com.lingyue.parse.vo.ParseTaskCenterVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 解析控制器
 */
@RestController
@RequestMapping("/parse")
@RequiredArgsConstructor
@Tag(name = "解析任务", description = "解析任务启动与状态查询接口")
public class ParseController {

    private final ParseTaskExecutor parseTaskExecutor;
    private final ParseTaskCenterService taskCenterService;
    private final WordStructuredExtractionService wordStructuredExtractionService;

    /**
     * 启动解析
     *
     * @param documentId 文档ID
     * @param filePath 原始文件路径
     */
    @PostMapping("/start")
    @Operation(summary = "启动解析任务")
    public AjaxResult<?> startParse(
            @Parameter(description = "文档ID", required = true)
            @RequestParam("documentId") String documentId,
            @Parameter(description = "原始文件路径", required = true)
            @RequestParam("filePath") String filePath) {

        parseTaskExecutor.submitParseTask(documentId, filePath);
        return AjaxResult.success("解析任务已提交");
    }

    /**
     * 查询解析状态（按文档ID）
     */
    @GetMapping("/status/{documentId}")
    @Operation(summary = "查询解析任务状态")
    public AjaxResult<?> getParseStatus(@PathVariable String documentId) {
        ParseTaskCenterVO detail = taskCenterService.getTaskDetailByDocumentId(documentId);
        if (detail == null) {
            return AjaxResult.error("解析任务不存在");
        }
        return AjaxResult.success(detail);
    }
    
    /**
     * 获取 Word 文档结构化内容
     * 包含段落、图片、表格的顺序和位置信息
     */
    @GetMapping("/structured/{documentId}")
    @Operation(summary = "获取Word文档结构化内容", description = "提取Word文档的段落、图片、表格，保持原始排版结构")
    public AjaxResult<?> getStructuredContent(
            @Parameter(description = "文档ID", required = true)
            @PathVariable String documentId,
            @Parameter(description = "Word文件路径", required = true)
            @RequestParam("filePath") String filePath) {
        
        WordStructuredExtractionService.WordStructuredResult result = 
                wordStructuredExtractionService.extractStructured(filePath, documentId);
        return AjaxResult.success(result);
    }
}

