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.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.ApiResponseHandler;
import com.example.demo.util.JwtUtils;

/**
 * API测试控制器
 * 演示如何使用改进的API调用和返回值处理
 */
@RestController
@RequestMapping("/api/test")
public class ApiTestController {

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

    @Autowired
    private ApiResponseHandler apiResponseHandler;

    @Autowired
    private JwtUtils jwtUtils;

    @Value("${ai.api.base-url:http://116.62.4.26:8081}")
    private String aiApiBaseUrl;

    @Value("${ai.api.key:ak_5f13ec469e6047d5b8155c3cc91350e2}")
    private String aiApiKey;

    /**
     * 获取视频列表 - 演示GET API调用
     */
    @GetMapping("/videos")
    public ResponseEntity<Map<String, Object>> getVideos(
            @RequestHeader("Authorization") String token) {
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                return ResponseEntity.status(401)
                    .body(apiResponseHandler.createErrorResponse("用户未登录"));
            }

            // 调用API获取视频列表
            Map<String, Object> result = apiResponseHandler.getVideoList(aiApiKey, aiApiBaseUrl);
            
            return ResponseEntity.ok(apiResponseHandler.createSuccessResponse(result));
            
        } catch (Exception e) {
            logger.error("获取视频列表失败", e);
            return ResponseEntity.status(500)
                .body(apiResponseHandler.createErrorResponse("获取视频列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取任务状态 - 演示带参数的GET API调用
     */
    @GetMapping("/tasks/{taskId}/status")
    public ResponseEntity<Map<String, Object>> getTaskStatus(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                return ResponseEntity.status(401)
                    .body(apiResponseHandler.createErrorResponse("用户未登录"));
            }

            // 调用API获取任务状态
            Map<String, Object> result = apiResponseHandler.getTaskStatus(taskId, aiApiKey, aiApiBaseUrl);
            
            return ResponseEntity.ok(apiResponseHandler.createSuccessResponse(result));
            
        } catch (Exception e) {
            logger.error("获取任务状态失败", e);
            return ResponseEntity.status(500)
                .body(apiResponseHandler.createErrorResponse("获取任务状态失败: " + e.getMessage()));
        }
    }

    /**
     * 提交测试任务 - 演示POST API调用
     */
    @PostMapping("/submit-task")
    public ResponseEntity<Map<String, Object>> submitTestTask(
            @RequestBody Map<String, Object> request,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                return ResponseEntity.status(401)
                    .body(apiResponseHandler.createErrorResponse("用户未登录"));
            }

            // 准备请求参数
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("modelName", request.getOrDefault("modelName", "default-model"));
            requestBody.put("prompt", request.get("prompt"));
            requestBody.put("aspectRatio", request.getOrDefault("aspectRatio", "16:9"));
            requestBody.put("imageToVideo", request.getOrDefault("imageToVideo", false));

            // 调用API提交任务
            String url = aiApiBaseUrl + "/user/ai/tasks/submit";
            Map<String, Object> result = apiResponseHandler.callApi(url, aiApiKey, requestBody);
            
            return ResponseEntity.ok(apiResponseHandler.createSuccessResponse(result));
            
        } catch (Exception e) {
            logger.error("提交测试任务失败", e);
            return ResponseEntity.status(500)
                .body(apiResponseHandler.createErrorResponse("提交测试任务失败: " + e.getMessage()));
        }
    }

    /**
     * 直接调用外部API - 演示原始Unirest调用
     */
    @GetMapping("/external-api")
    public ResponseEntity<Map<String, Object>> callExternalApi(
            @RequestHeader("Authorization") String token) {
        
        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                return ResponseEntity.status(401)
                    .body(apiResponseHandler.createErrorResponse("用户未登录"));
            }

            // 使用您提供的代码模式
            String url = aiApiBaseUrl + "/v1/videos/";
            
            // 这里演示您提到的代码模式
            // Unirest.setTimeouts(0, 0);
            // HttpResponse<String> response = Unirest.get(url)
            //     .header("Authorization", "Bearer " + aiApiKey)
            //     .asString();
            
            // 使用我们的封装方法
            Map<String, Object> result = apiResponseHandler.callGetApi(url, aiApiKey);
            
            return ResponseEntity.ok(apiResponseHandler.createSuccessResponse(result));
            
        } catch (Exception e) {
            logger.error("调用外部API失败", e);
            return ResponseEntity.status(500)
                .body(apiResponseHandler.createErrorResponse("调用外部API失败: " + e.getMessage()));
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }
}

