package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.model.entity.AiModel;
import com.agent.management.service.AiModelService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/models")
@RequiredArgsConstructor
public class AiModelController {

    private final AiModelService modelService;

    @GetMapping
    public Result<List<AiModel>> list() {
        List<AiModel> models = modelService.listModels();
        for (AiModel m : models) {
            m.setApiKey(maskApiKey(m.getApiKey()));
        }
        return Result.success(models);
    }

    @GetMapping("/{id}")
    public Result<AiModel> get(@PathVariable Long id) {
        AiModel model = modelService.getModel(id);
        model.setApiKey(maskApiKey(model.getApiKey()));
        return Result.success(model);
    }

    @PostMapping
    public Result<AiModel> create(@RequestBody ModelReq req) {
        AiModel model = new AiModel();
        model.setName(req.getName());
        model.setBaseUrl(req.getBaseUrl());
        model.setCompletionsPath(req.getCompletionsPath());
        model.setApiKey(req.getApiKey());
        model.setModelName(req.getModelName());
        model.setTemperature(req.getTemperature() != null ? req.getTemperature() : 0.3);
        model.setIsDefault(req.getIsDefault() != null ? req.getIsDefault() : false);
        AiModel saved = modelService.createModel(model);
        saved.setApiKey(maskApiKey(saved.getApiKey()));
        return Result.success(saved);
    }

    @PostMapping("/{id}/edit")
    public Result<AiModel> update(@PathVariable Long id, @RequestBody ModelReq req) {
        AiModel model = new AiModel();
        model.setName(req.getName());
        model.setBaseUrl(req.getBaseUrl());
        model.setCompletionsPath(req.getCompletionsPath());
        model.setApiKey(req.getApiKey());
        model.setModelName(req.getModelName());
        model.setTemperature(req.getTemperature());
        model.setIsDefault(req.getIsDefault());
        AiModel saved = modelService.updateModel(id, model);
        saved.setApiKey(maskApiKey(saved.getApiKey()));
        return Result.success(saved);
    }

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

    /** 复制模型：以原模型为模板创建一条新记录，名称追加「（复制）」 */
    @PostMapping("/{id}/duplicate")
    public Result<AiModel> duplicate(@PathVariable Long id) {
        AiModel saved = modelService.duplicateModel(id);
        saved.setApiKey(maskApiKey(saved.getApiKey()));
        return Result.success(saved);
    }

    @PostMapping("/{id}/default")
    public Result<Void> setDefault(@PathVariable Long id) {
        modelService.setDefault(id);
        return Result.success(null);
    }

    /**
     * 批量更新模型调用优先级
     * body: [{ id: 1, priority: 0 }, { id: 2, priority: 1 }, ...]
     * priority=0 的模型自动设为默认模型
     */
    @PostMapping("/priorities")
    public Result<Void> updatePriorities(@RequestBody List<Map<String, Object>> priorities) {
        modelService.updatePriorities(priorities);
        return Result.success(null);
    }

    /**
     * 测试已保存模型的连接
     */
    @PostMapping("/{id}/test")
    public Result<Map<String, Object>> testSaved(@PathVariable Long id) {
        return Result.success(modelService.testConnection(id));
    }

    /**
     * 测试自定义配置的连接（无需保存，用于新建/编辑时预验证）
     */
    @PostMapping("/test")
    public Result<Map<String, Object>> testConnection(@RequestBody ModelReq req) {
        AiModel model = new AiModel();
        model.setBaseUrl(req.getBaseUrl());
        model.setCompletionsPath(req.getCompletionsPath());
        model.setApiKey(req.getApiKey());
        model.setModelName(req.getModelName());
        model.setTemperature(req.getTemperature() != null ? req.getTemperature() : 0.3);
        return Result.success(modelService.testConnection(model));
    }

    /**
     * 获取接口下可用的模型列表
     */
    @PostMapping("/fetch-models")
    public Result<List<String>> fetchModels(@RequestBody ModelReq req) {
        AiModel model = new AiModel();
        model.setBaseUrl(req.getBaseUrl());
        model.setApiKey(req.getApiKey());
        return Result.success(modelService.fetchAvailableModels(model));
    }

    @Data
    public static class ModelReq {
        private String name;
        private String baseUrl;
        private String completionsPath;
        private String apiKey;
        private String modelName;
        private Double temperature;
        private Boolean isDefault;
    }

    /** 脱敏：保留前4位和后4位 */
    private String maskApiKey(String key) {
        if (key == null || key.length() <= 12) return "****";
        return key.substring(0, 4) + "****" + key.substring(key.length() - 4);
    }
}
