package com.erp.ai.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.ai.dto.SwitchModelRequest;
import com.erp.ai.service.AIModelService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * AI模型控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ai/models")
@RequiredArgsConstructor
public class AIModelController {

    private final AIModelService aiModelService;

    /**
     * 获取可用模型列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getModels() {
        log.info("获取可用模型列表");
        try {
            Map<String, Object> models = aiModelService.getModels();
            return ResponseEntity.ok(ApiResponse.success(models));
        } catch (Exception e) {
            log.error("获取模型列表失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "获取模型列表失败: " + e.getMessage()));
        }
    }

    /**
     * 切换模型
     */
    @PostMapping("/switch")
    public ResponseEntity<ApiResponse<Map<String, Object>>> switchModel(
            @RequestHeader("X-User-Id") Long userId,
            @Valid @RequestBody SwitchModelRequest request) {
        log.info("切换模型: userId={}, service={}, model={}", userId, request.getService(), request.getModel());

        try {
            Map<String, Object> result = aiModelService.switchModel(
                    request.getService(), request.getModel(), userId);

            if (Boolean.TRUE.equals(result.get("success"))) {
                return ResponseEntity.ok(ApiResponse.success("模型切换成功", result));
            } else {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error(400, (String) result.get("error")));
            }
        } catch (Exception e) {
            log.error("切换模型失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "切换模型失败: " + e.getMessage()));
        }
    }

    /**
     * 获取当前模型信息
     */
    @GetMapping("/current")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getCurrentModel() {
        log.info("获取当前模型信息");
        try {
            Map<String, Object> modelInfo = aiModelService.getCurrentModel();
            return ResponseEntity.ok(ApiResponse.success(modelInfo));
        } catch (Exception e) {
            log.error("获取当前模型失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "获取当前模型失败: " + e.getMessage()));
        }
    }

    /**
     * 测试模型连接
     */
    @PostMapping("/test")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testModel(
            @RequestParam(required = false) String service,
            @RequestParam(required = false) String model) {
        log.info("测试模型连接: service={}, model={}", service, model);

        try {
            Map<String, Object> testResult = aiModelService.testModel(service, model);
            String message = Boolean.TRUE.equals(testResult.get("success"))
                    ? "连接测试成功"
                    : "连接测试失败";
            return ResponseEntity.ok(ApiResponse.success(message, testResult));
        } catch (Exception e) {
            log.error("测试模型连接失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "测试模型连接失败: " + e.getMessage()));
        }
    }

    /**
     * 获取模型使用统计
     */
    @GetMapping("/statistics")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getModelStatistics(
            @RequestParam(defaultValue = "day") String period) {
        log.info("获取模型使用统计: period={}", period);

        try {
            Map<String, Object> statistics = aiModelService.getModelStatistics(period);
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            log.error("获取模型统计失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "获取模型统计失败: " + e.getMessage()));
        }
    }

    /**
     * 获取模型推荐
     */
    @GetMapping("/recommendations")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getModelRecommendations() {
        log.info("获取模型推荐");

        try {
            Map<String, Object> recommendations = aiModelService.getModelRecommendations();
            return ResponseEntity.ok(ApiResponse.success(recommendations));
        } catch (Exception e) {
            log.error("获取模型推荐失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "获取模型推荐失败: " + e.getMessage()));
        }
    }
}
