package com.dora.service.impl;

import com.dora.dto.api.ApiRequest;
import com.dora.dto.api.ApiResponse;
import com.dora.dto.api.ContentItem;
import com.dora.dto.api.Message;
import com.dora.entity.AiTask;
import com.dora.service.ThirdPartyApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 第三方AI API服务实现
 * 
 * <p>支持以下功能：
 * <ul>
 *   <li>文生图：纯文本提示词生成图片</li>
 *   <li>文生视频：纯文本提示词生成视频</li>
 *   <li>图生视频：参考图片 + 文本描述生成视频</li>
 * </ul>
 * 
 * @author 1818AI
 * @since 2025-10-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ThirdPartyApiServiceImpl implements ThirdPartyApiService {

    private final RestTemplate restTemplate;

    @Value("${ai.api.base-url}")
    private String apiBaseUrl;

    @Value("${ai.api.api-key}")
    private String apiKey;

    @Override
    public ApiResponse executeGeneration(String modelName, String prompt) {
        return executeGeneration(modelName, prompt, null);
    }

    @Override
    public ApiResponse executeGeneration(String modelName, String prompt, String imageParam) {
        String apiUrl = apiBaseUrl;

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(apiKey);

        Message userMessage;
        
        // 判断是否为图生视频（有图片参数）
        if (imageParam != null && !imageParam.trim().isEmpty()) {
            log.info("图生视频任务，模型: {}, 图片参数长度: {}", modelName, imageParam.length());
            
            // 构建复杂内容：文本 + 图片
            List<ContentItem> contentItems = new ArrayList<>();
            contentItems.add(ContentItem.text(prompt));
            contentItems.add(ContentItem.imageUrl(imageParam));
            
            userMessage = new Message("user", contentItems);
        } else {
            // 普通文生图/视频
            log.info("文生图/视频任务，模型: {}", modelName);
            userMessage = new Message("user", prompt);
        }

        ApiRequest requestPayload = new ApiRequest(modelName, Collections.singletonList(userMessage), false);
        HttpEntity<ApiRequest> entity = new HttpEntity<>(requestPayload, headers);

        try {
            ApiResponse response = restTemplate.postForObject(apiUrl, entity, ApiResponse.class);
            log.info("第三方API调用成功，模型: {}", modelName);
            return response;
        } catch (Exception e) {
            log.error("第三方API调用失败，模型: {}, 错误: {}", modelName, e.getMessage());
            throw new RuntimeException("第三方API调用失败: " + e.getMessage(), e);
        }
    }

    @Override
    public ApiResponse executeGenerationForTask(AiTask task) {
        String imageParam = null;
        
        // 优先使用imageUrl，其次使用imageBase64
        if (task.getImageUrl() != null && !task.getImageUrl().trim().isEmpty()) {
            imageParam = task.getImageUrl();
        } else if (task.getImageBase64() != null && !task.getImageBase64().trim().isEmpty()) {
            imageParam = task.getImageBase64();
        }
        
        return executeGeneration(task.getModelName(), task.getPrompt(), imageParam);
    }
}
