package com.erp.ai.controller;

import com.erp.ai.dto.*;
import com.erp.ai.entity.AIConversation;
import com.erp.ai.service.AIAssistantService;
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.List;
import com.erp.common.core.model.PageResponse;
import java.util.Map;
import com.erp.common.core.model.ApiResponse;

/**
 * AI助手控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AIAssistantController {

    private final AIAssistantService aiAssistantService;

    /**
     * AI对话
     */
    @PostMapping("/chat")
    public ResponseEntity<ApiResponse<AIChatResponse>> chat(
            @RequestHeader("X-User-Id") Long userId,
            @Valid @RequestBody AIChatRequest request) {
        log.info("AI对话请求: userId={}, conversationId={}", userId, request.getConversationId());

        try {
            AIChatResponse response = aiAssistantService.chat(userId, request);
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            log.error("AI对话失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "AI对话失败: " + e.getMessage()));
        }
    }

    /**
     * 执行AI任务
     */
    @PostMapping("/tasks/execute")
    public ResponseEntity<ApiResponse<Map<String, Object>>> executeTask(
            @RequestHeader("X-User-Id") Long userId,
            @Valid @RequestBody AITaskRequest request) {
        log.info("AI任务执行: userId={}, task={}", userId, request.getTask());

        try {
            Map<String, Object> result = aiAssistantService.executeTask(
                    userId, request.getTask(), request.getParameters());
            return ResponseEntity.ok(ApiResponse.success("任务执行成功", result));
        } catch (Exception e) {
            log.error("AI任务执行失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "任务执行失败: " + e.getMessage()));
        }
    }

    /**
     * 获取对话列表
     */
    @GetMapping("/conversations")
    public ResponseEntity<ApiResponse<PageResponse<AIConversation>>> getConversations(
            @RequestHeader("X-User-Id") Long userId,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit) {
        log.info("获取对话列表: userId={}, status={}, keyword={}, page={}, limit={}",
                userId, status, keyword, page, limit);

        PageResponse<AIConversation> conversations = aiAssistantService.getConversations(
                userId, status, keyword, page, limit);
        return ResponseEntity.ok(ApiResponse.success(conversations));
    }

    /**
     * 获取对话详情
     */
    @GetMapping("/conversations/{id}")
    public ResponseEntity<ApiResponse<AIConversation>> getConversation(
            @RequestHeader("X-User-Id") Long userId,
            @PathVariable Long id) {
        log.info("获取对话详情: userId={}, id={}", userId, id);

        try {
            AIConversation conversation = aiAssistantService.getConversation(userId, id);
            return ResponseEntity.ok(ApiResponse.success(conversation));
        } catch (Exception e) {
            log.error("获取对话详情失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, e.getMessage()));
        }
    }

    /**
     * 删除对话
     */
    @DeleteMapping("/conversations/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteConversation(
            @RequestHeader("X-User-Id") Long userId,
            @PathVariable Long id) {
        log.info("删除对话: userId={}, id={}", userId, id);

        try {
            aiAssistantService.deleteConversation(userId, id);
            return ResponseEntity.ok(ApiResponse.success("对话删除成功", null));
        } catch (Exception e) {
            log.error("删除对话失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "删除失败: " + e.getMessage()));
        }
    }

    /**
     * 清空对话消息
     */
    @DeleteMapping("/conversations/{id}/messages")
    public ResponseEntity<ApiResponse<Void>> clearConversation(
            @RequestHeader("X-User-Id") Long userId,
            @PathVariable Long id) {
        log.info("清空对话消息: userId={}, id={}", userId, id);

        try {
            aiAssistantService.clearConversation(userId, id);
            return ResponseEntity.ok(ApiResponse.success("对话消息已清空", null));
        } catch (Exception e) {
            log.error("清空对话失败: {}", e.getMessage());
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error(500, "清空失败: " + e.getMessage()));
        }
    }

    /**
     * 获取AI能力列表
     */
    @GetMapping("/capabilities")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getCapabilities() {
        log.info("获取AI能力列表");
        List<Map<String, Object>> capabilities = aiAssistantService.getCapabilities();
        return ResponseEntity.ok(ApiResponse.success(capabilities));
    }

    /**
     * 获取使用统计
     */
    @GetMapping("/statistics")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUsageStatistics(
            @RequestHeader("X-User-Id") Long userId) {
        log.info("获取使用统计: userId={}", userId);
        Map<String, Object> statistics = aiAssistantService.getUsageStatistics(userId);
        return ResponseEntity.ok(ApiResponse.success(statistics));
    }

    /**
     * 测试AI连接
     */
    @GetMapping("/test")
    public ResponseEntity<ApiResponse<Map<String, Object>>> testConnection() {
        log.info("测试AI连接");
        // 使用AIModelService进行测试
        return ResponseEntity.ok(ApiResponse.success(Map.of(
            "status", "ok",
            "message", "AI服务连接正常"
        )));
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("AI Service is healthy");
    }
}
