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.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
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.service.RealAIService;

@RestController
@RequestMapping("/api/prompt")
public class PromptOptimizerApiController {

    private static final Logger logger = LoggerFactory.getLogger(PromptOptimizerApiController.class);

    @Autowired
    private RealAIService realAIService;

    /**
     * 优化提示词
     * 
     * @param request 包含prompt和type的请求体
     * @param authentication 用户认证信息
     * @return 优化后的提示词
     */
    @PostMapping("/optimize")
    public ResponseEntity<?> optimizePrompt(
            @RequestBody Map<String, Object> request,
            Authentication authentication) {
        try {
            String username = (authentication != null) ? authentication.getName() : "anonymous";
            logger.info("收到优化提示词请求，用户: {}", username);

            // 从请求中提取参数
            String prompt = (String) request.get("prompt");
            String type = (String) request.getOrDefault("type", "text-to-video");

            // 参数验证
            if (prompt == null || prompt.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "提示词不能为空"));
            }

            // 长度验证（防止过长）
            if (prompt.length() > 2000) {
                return ResponseEntity.badRequest()
                    .body(Map.of("success", false, "message", "提示词过长，请控制在2000字符以内"));
            }

            // 验证type是否有效
            if (!isValidType(type)) {
                logger.warn("无效的优化类型: {}, 使用默认类型: text-to-video", type);
                type = "text-to-video"; // 默认类型
            }

            // 调用优化服务
            String optimizedPrompt = realAIService.optimizePrompt(prompt.trim(), type);
            
            // 检查优化是否成功（如果返回原始提示词可能是失败）
            boolean optimized = !optimizedPrompt.equals(prompt.trim());

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", optimized ? "提示词优化成功" : "提示词优化完成（可能使用了原始提示词）");
            response.put("data", Map.of(
                "originalPrompt", prompt,
                "optimizedPrompt", optimizedPrompt,
                "type", type,
                "optimized", optimized
            ));

            logger.info("提示词优化完成，用户: {}, 类型: {}, 原始长度: {}, 优化后长度: {}", 
                username, type, prompt.length(), optimizedPrompt.length());

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            logger.error("参数错误: {}", e.getMessage());
            return ResponseEntity.badRequest()
                .body(Map.of("success", false, "message", "参数错误: " + e.getMessage()));
        } catch (Exception e) {
            logger.error("优化提示词失败", e);
            return ResponseEntity.internalServerError()
                .body(Map.of("success", false, "message", "优化提示词失败，请稍后重试"));
        }
    }

    /**
     * 验证类型是否有效
     */
    private boolean isValidType(String type) {
        return type != null && (
            type.equals("text-to-video") || 
            type.equals("image-to-video") || 
            type.equals("storyboard")
        );
    }
}

