package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.model.entity.GraphSource;
import com.agent.management.service.GraphSourceService;
import jakarta.validation.Valid;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 知识图谱源 CRUD + Cypher 查询 API
 */
@RestController
@RequestMapping("/api/kb/graphs")
@RequiredArgsConstructor
@Validated
public class GraphSourceController {

    private final GraphSourceService graphSourceService;

    @GetMapping
    public Result<List<GraphSource>> list() {
        return Result.success(graphSourceService.listAll());
    }

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

    @PostMapping
    public Result<GraphSource> create(@Valid @RequestBody GraphSource gs) {
        return Result.success(graphSourceService.create(gs));
    }

    @PutMapping("/{id}")
    public Result<GraphSource> update(@PathVariable Long id, @RequestBody GraphSource gs) {
        return Result.success(graphSourceService.update(id, gs));
    }

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

    /** 测试连接（不持久化，用于表单预检） */
    @PostMapping("/test")
    public Result<GraphSourceService.TestResult> test(@RequestBody GraphSource gs) {
        return Result.success(graphSourceService.testConnection(gs));
    }

    /** 测试已存在图谱源（持久化结果） */
    @PostMapping("/{id}/test")
    public Result<GraphSourceService.TestResult> testExisting(@PathVariable Long id) {
        return Result.success(graphSourceService.testExisting(id));
    }

    /**
     * 执行只读 Cypher 查询，返回 cytoscape elements
     */
    @PostMapping("/{id}/query")
    public Result<Map<String, Object>> query(
            @PathVariable Long id,
            @RequestBody QueryRequest req) {
        return Result.success(graphSourceService.executeQuery(id, req.getCypher()));
    }

    /** 列出图谱的所有 node labels（用于查询提示） */
    @GetMapping("/{id}/labels")
    public Result<List<String>> labels(@PathVariable Long id) {
        return Result.success(graphSourceService.listLabels(id));
    }

    @Data
    public static class QueryRequest {
        private String cypher;
    }
}
