package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.dto.SearchRequest;
import top.tqx.demo_1.dto.SearchResponse;
import top.tqx.demo_1.entity.User;
import top.tqx.demo_1.service.AuthService;
import top.tqx.demo_1.service.DepartmentService;
import top.tqx.demo_1.service.KnowledgeBasePathService;
import top.tqx.demo_1.service.SearchService;

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

@Tag(name = "知识检索", description = "知识库检索相关接口")
@RestController
@RequestMapping("/search")
@Slf4j
public class SearchController {

    @Autowired
    private SearchService searchService;

    @Autowired
    private AuthService authService;

    @Autowired
    private KnowledgeBasePathService knowledgeBasePathService;

    @Autowired
    private DepartmentService departmentService;

    @Operation(summary = "混合检索", description = "在知识库中进行混合检索（向量+关键词）")
    @PostMapping
    public Map<String, Object> search(@RequestBody SearchRequest request, HttpServletRequest httpRequest) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("知识检索: query={}, topK={}", request.getQuery(), request.getTopK());

            // 获取用户可访问的知识库
            if (request.getCollections() == null || request.getCollections().isEmpty()) {
                String authHeader = httpRequest.getHeader("Authorization");
                if (authHeader != null && authHeader.startsWith("Bearer ")) {
                    User user = authService.validateToken(authHeader.substring(7));
                    if (user != null) {
                        String deptCode = null;
                        if (user.getDeptId() != null) {
                            top.tqx.demo_1.entity.Department dept = departmentService.getDepartmentById(user.getDeptId());
                            if (dept != null) {
                                deptCode = dept.getDeptCode();
                            }
                        }
                        List<String> collections = knowledgeBasePathService.getUserAccessibleKnowledgeBaseNames(user.getId(), user.getDeptId(), deptCode);
                        request.setCollections(collections);
                    }
                }
            }

            SearchResponse response = searchService.search(request);
            result.put("success", true);
            result.put("contexts", response.getContexts());
            result.put("metadatas", response.getMetadatas());
            result.put("scores", response.getScores());
        } catch (Exception e) {
            log.error("知识检索失败", e);
            result.put("success", false);
            result.put("message", "知识检索失败: " + e.getMessage());
        }
        return result;
    }
}
