package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.config.KbProperties;
import com.agent.management.model.entity.KbDocument;
import com.agent.management.service.DocumentService;
import com.agent.management.service.DocumentService.ChunkView;
import com.agent.management.service.DocumentService.PageResult;
import com.agent.management.service.VectorStoreService;
import com.agent.management.service.impl.EmbeddingBridgeClient;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 知识库文档管理 API
 */
@RestController
@RequestMapping("/api/kb/documents")
@RequiredArgsConstructor
public class KbDocumentController {

    private final DocumentService documentService;
    private final KbProperties kbProps;
    private final EmbeddingBridgeClient bridgeClient;
    private final VectorStoreService vectorStoreService;

    /**
     * 上传文档（multipart/form-data）
     */
    @PostMapping("/upload")
    public Result<KbDocument> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "categoryId", required = false) Long categoryId) {
        if (!kbProps.isEnabled()) {
            return Result.error(503, "知识库子系统已禁用");
        }
        return Result.success(documentService.upload(file, categoryId));
    }

    @GetMapping
    public Result<PageResult> list(
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size) {
        return Result.success(documentService.list(categoryId, keyword, page, size));
    }

    @GetMapping("/{id}")
    public Result<KbDocument> get(@PathVariable Long id) {
        return Result.success(documentService.get(id));
    }

    @GetMapping("/{id}/chunks")
    public Result<List<ChunkView>> chunks(@PathVariable Long id) {
        return Result.success(documentService.listChunks(id));
    }

    @PostMapping("/{id}/revectorize")
    public Result<KbDocument> revectorize(@PathVariable Long id) {
        return Result.success(documentService.revectorize(id));
    }

    @PostMapping("/{id}/vectorize")
    public Result<KbDocument> vectorizeDocument(@PathVariable Long id) {
        return Result.success(documentService.vectorizeDocument(id));
    }

    @PostMapping("/chunks/{chunkId}/vectorize")
    public Result<KbDocument> vectorizeChunk(@PathVariable Long chunkId) {
        return Result.success(documentService.vectorizeChunk(chunkId));
    }

    @PostMapping("/{id}/move")
    public Result<KbDocument> move(@PathVariable Long id, @RequestBody MoveReq req) {
        return Result.success(documentService.move(id, req.getCategoryId()));
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        documentService.delete(id);
        return Result.success(null);
    }

    /**
     * 子系统状态（前端用作环境提示）
     */
    @GetMapping("/_dependencies")
    public Result<Map<String, Boolean>> dependencies() {
        return Result.success(Map.of(
                "kbEnabled", kbProps.isEnabled(),
                "embeddingAvailable", bridgeClient.health(),
                "vectorStoreAvailable", vectorStoreService.isAvailable()
        ));
    }

    @lombok.Data
    public static class MoveReq {
        private Long categoryId;
    }
}
