package com.lingyue.graph.controller;

import com.lingyue.common.domain.AjaxResult;
import com.lingyue.graph.entity.TextChunk;
import com.lingyue.graph.service.RAGService;
import com.lingyue.graph.service.TextChunkService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * RAG API 控制器
 *
 * @author lingyue
 * @since 2026-01-15
 */
@Slf4j
@RestController
@RequestMapping("/api/rag")
@RequiredArgsConstructor
@Tag(name = "RAG接口", description = "RAG向量检索与问答")
public class RAGController {

    private final RAGService ragService;
    private final TextChunkService textChunkService;

    /**
     * 索引文档（分块+向量化）
     */
    @PostMapping("/index")
    @Operation(summary = "索引文档", description = "将文档进行分块和向量化存储")
    public AjaxResult<IndexResponse> indexDocument(@RequestBody IndexRequest request) {
        log.info("索引文档请求: documentId={}", request.getDocumentId());

        int chunkCount = ragService.indexDocument(
                request.getDocumentId(),
                request.getTextStorageId(),
                request.getText()
        );

        IndexResponse response = new IndexResponse();
        response.setDocumentId(request.getDocumentId());
        response.setChunkCount(chunkCount);
        response.setMessage("索引完成");

        return AjaxResult.success(response);
    }

    /**
     * RAG 问答
     */
    @PostMapping("/query")
    @Operation(summary = "RAG问答", description = "基于向量检索的智能问答")
    public AjaxResult<RAGService.RAGResult> query(@RequestBody QueryRequest request) {
        log.info("RAG查询请求: question={}", request.getQuestion());

        RAGService.RAGResult result = ragService.query(
                request.getQuestion(),
                request.getDocumentId(),
                request.getTopK()
        );

        return AjaxResult.success(result);
    }

    /**
     * 获取文档分块
     */
    @GetMapping("/chunks/{documentId}")
    @Operation(summary = "获取文档分块", description = "获取指定文档的所有文本分块")
    public AjaxResult<List<TextChunk>> getChunks(
            @PathVariable @Parameter(description = "文档ID") String documentId) {

        List<TextChunk> chunks = textChunkService.getChunksByDocumentId(documentId);
        return AjaxResult.success(chunks);
    }

    /**
     * 删除文档索引
     */
    @DeleteMapping("/index/{documentId}")
    @Operation(summary = "删除文档索引", description = "删除指定文档的所有分块和向量")
    public AjaxResult<Void> deleteIndex(
            @PathVariable @Parameter(description = "文档ID") String documentId) {

        ragService.deleteIndex(documentId);
        return AjaxResult.success("索引删除成功", null);
    }

    /**
     * 获取文档分块统计
     */
    @GetMapping("/stats/{documentId}")
    @Operation(summary = "获取文档分块统计", description = "获取指定文档的分块数量")
    public AjaxResult<StatsResponse> getStats(
            @PathVariable @Parameter(description = "文档ID") String documentId) {

        int chunkCount = textChunkService.countByDocumentId(documentId);

        StatsResponse response = new StatsResponse();
        response.setDocumentId(documentId);
        response.setChunkCount(chunkCount);

        return AjaxResult.success(response);
    }

    // ==================== 请求/响应 DTO ====================

    @lombok.Data
    public static class IndexRequest {
        @Parameter(description = "文档ID", required = true)
        private String documentId;

        @Parameter(description = "文本存储ID")
        private String textStorageId;

        @Parameter(description = "文档文本内容", required = true)
        private String text;
    }

    @lombok.Data
    public static class QueryRequest {
        @Parameter(description = "用户问题", required = true)
        private String question;

        @Parameter(description = "文档ID（可选，不传则全局检索）")
        private String documentId;

        @Parameter(description = "检索数量，默认3")
        private Integer topK;
    }

    @lombok.Data
    public static class IndexResponse {
        private String documentId;
        private Integer chunkCount;
        private String message;
    }

    @lombok.Data
    public static class StatsResponse {
        private String documentId;
        private Integer chunkCount;
    }
}
