package com.example.demo.controller;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.config.DynamicApiConfig;
import com.example.demo.model.SystemSettings;
import com.example.demo.service.SystemSettingsService;

/**
 * API密钥管理控制器
 * 配置保存到数据库，支持运行时更新，重启后自动加载
 */
@RestController
@RequestMapping("/api/api-key")
@CrossOrigin(origins = "*")
public class ApiKeyController {

    private static final Logger logger = LoggerFactory.getLogger(ApiKeyController.class);
    
    @Autowired
    private DynamicApiConfig dynamicApiConfig;
    
    @Autowired
    private SystemSettingsService systemSettingsService;

    /**
     * 获取当前API密钥配置（仅显示部分，用于验证）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getApiKey() {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 从动态配置获取当前使用的 API Key
            String currentApiKey = dynamicApiConfig.getApiKey();
            String currentApiBaseUrl = dynamicApiConfig.getApiBaseUrl();
            
            // 只返回密钥的前4位和后4位，中间用*代替
            if (currentApiKey != null && currentApiKey.length() > 8) {
                String masked = currentApiKey.substring(0, 4) + "****" + currentApiKey.substring(currentApiKey.length() - 4);
                response.put("maskedKey", masked);
            } else {
                response.put("maskedKey", "****");
            }
            
            response.put("apiBaseUrl", currentApiBaseUrl);
            
            // 从数据库获取 Token 过期时间
            SystemSettings settings = systemSettingsService.getOrCreate();
            response.put("tokenExpireHours", settings.getTokenExpireHours());
            
            response.put("success", true);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取API密钥失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取API密钥失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 更新API密钥配置到数据库（立即生效，重启后自动加载）
     */
    @PutMapping
    public ResponseEntity<Map<String, Object>> updateApiKey(@RequestBody Map<String, Object> request) {
        try {
            String newApiKey = (String) request.get("apiKey");
            String newApiBaseUrl = (String) request.get("apiBaseUrl");
            Object tokenExpireObj = request.get("tokenExpireHours");
            
            // 验证API密钥
            if (newApiKey != null && newApiKey.trim().isEmpty()) {
                newApiKey = null;
            }
            
            // 验证API基础URL
            if (newApiBaseUrl != null && newApiBaseUrl.trim().isEmpty()) {
                newApiBaseUrl = null;
            }
            
            // 验证Token过期时间
            Integer tokenExpireHours = null;
            if (tokenExpireObj != null) {
                if (tokenExpireObj instanceof Number) {
                    tokenExpireHours = ((Number) tokenExpireObj).intValue();
                } else if (tokenExpireObj instanceof String) {
                    try {
                        tokenExpireHours = Integer.parseInt((String) tokenExpireObj);
                    } catch (NumberFormatException e) {
                        // 忽略无效值
                    }
                }
                // 验证范围
                if (tokenExpireHours != null && (tokenExpireHours < 1 || tokenExpireHours > 720)) {
                    tokenExpireHours = null;
                }
            }
            
            // 如果都没有提供，返回错误
            if (newApiKey == null && newApiBaseUrl == null && tokenExpireHours == null) {
                Map<String, Object> error = new HashMap<>();
                error.put("error", "至少需要提供一个配置项");
                error.put("message", "请提供API密钥、API基础URL或Token过期时间");
                return ResponseEntity.badRequest().body(error);
            }

            // 获取系统设置
            SystemSettings settings = systemSettingsService.getOrCreate();
            
            StringBuilder message = new StringBuilder();
            
            // 更新API密钥
            if (newApiKey != null) {
                newApiKey = newApiKey.trim();
                settings.setAiApiKey(newApiKey);
                
                // 动态更新运行时配置，立即生效
                dynamicApiConfig.updateApiKey(newApiKey);
                
                logger.info("✅ API密钥已保存到数据库并立即生效");
                message.append("API密钥已更新。");
            }
            
            // 更新API基础URL
            if (newApiBaseUrl != null) {
                newApiBaseUrl = newApiBaseUrl.trim();
                settings.setAiApiBaseUrl(newApiBaseUrl);
                
                // 动态更新运行时配置，立即生效
                dynamicApiConfig.updateApiBaseUrl(newApiBaseUrl);
                
                logger.info("✅ API基础URL已保存到数据库并立即生效: {}", newApiBaseUrl);
                message.append("API基础URL已更新。");
            }
            
            // 更新Token过期时间
            if (tokenExpireHours != null) {
                settings.setTokenExpireHours(tokenExpireHours);
                logger.info("✅ Token过期时间已保存到数据库: {} 小时", tokenExpireHours);
                message.append("Token过期时间已更新为" + tokenExpireHours + "小时。");
            }
            
            // 保存到数据库
            systemSettingsService.update(settings);
            
            message.append("配置已保存到数据库，立即生效且重启后自动加载。");

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", message.toString());

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("更新配置失败", e);
            Map<String, Object> error = new HashMap<>();
            error.put("error", "更新配置失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}

