package com.lingyue.graph.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.graph.service.DocumentBlockGeneratorService;
import com.lingyue.graph.service.DocumentBlockGeneratorService.BlockDTO;
import com.lingyue.graph.service.GraphNerService;
import com.lingyue.graph.service.NerToBlockService;
import com.lingyue.graph.service.NerToBlockService.TextElementDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * NER 到 Block 转换控制器
 * 
 * 提供将 NER 结果转换为结构化 Block 的接口
 * 
 * @author lingyue
 * @since 2026-01-21
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/ner")
@RequiredArgsConstructor
@Tag(name = "NER Block 转换", description = "NER 结果转换为结构化 Block")
public class NerBlockController {
    
    private final GraphNerService graphNerService;
    private final NerToBlockService nerToBlockService;
    private final DocumentBlockGeneratorService blockGeneratorService;
    
    /**
     * 将文本和实体转换为 TextElement 列表
     */
    @PostMapping("/convert-to-elements")
    @Operation(summary = "转换为 TextElement", description = "将文本和 NER 实体转换为 TextElement 列表")
    public AjaxResult<?> convertToElements(@RequestBody ConvertRequest request) {
        try {
            List<TextElementDTO> elements = nerToBlockService.convertToTextElements(
                    request.getText(), request.getEntities());
            return AjaxResult.success(elements);
        } catch (Exception e) {
            log.error("转换失败: {}", e.getMessage(), e);
            return AjaxResult.error("转换失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成完整的文档块结构
     */
    @PostMapping("/generate-blocks")
    @Operation(summary = "生成文档块", description = "将文本和 NER 实体生成完整的 Block 结构")
    public AjaxResult<?> generateBlocks(@RequestBody GenerateBlocksRequest request) {
        try {
            List<BlockDTO> blocks = blockGeneratorService.generateBlocks(
                    request.getDocumentId(), request.getText(), request.getEntities());
            return AjaxResult.success(blocks);
        } catch (Exception e) {
            log.error("生成块失败: {}", e.getMessage(), e);
            return AjaxResult.error("生成块失败: " + e.getMessage());
        }
    }
    
    /**
     * 从已存储的文档生成块结构
     */
    @PostMapping("/documents/{documentId}/generate-blocks")
    @Operation(summary = "从文档生成块", description = "读取已存储的文档文本，结合 NER 结果生成 Block 结构")
    public AjaxResult<?> generateBlocksFromDocument(
            @PathVariable String documentId,
            @RequestBody(required = false) List<Map<String, Object>> entities) {
        try {
            // 获取文档文本
            String text = graphNerService.getDocumentText(documentId);
            
            // 如果没有提供实体，尝试从图数据库获取
            if (entities == null || entities.isEmpty()) {
                // TODO: 从 GraphNode 表获取实体并转换
                log.info("未提供实体，生成纯文本块: documentId={}", documentId);
            }
            
            List<BlockDTO> blocks = blockGeneratorService.generateBlocks(documentId, text, entities);
            return AjaxResult.success(blocks);
        } catch (Exception e) {
            log.error("从文档生成块失败: documentId={}, error={}", documentId, e.getMessage(), e);
            return AjaxResult.error("生成失败: " + e.getMessage());
        }
    }
    
    // ==================== 请求 DTO ====================
    
    @Data
    public static class ConvertRequest {
        private String text;
        private List<Map<String, Object>> entities;
    }
    
    @Data
    public static class GenerateBlocksRequest {
        private String documentId;
        private String text;
        private List<Map<String, Object>> entities;
    }
}
