package com.dora.service.provider.impl;

import com.dora.dto.api.ApiResponse;
import com.dora.dto.provider.*;
import com.dora.entity.AiTask;
import com.dora.service.ThirdPartyApiService;
import com.dora.service.provider.AIProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * OpenAI格式API适配器
 * 
 * <p>适配所有符合OpenAI格式的API，包括：
 * <ul>
 *   <li>api.apiyi.com</li>
 *   <li>OpenAI官方API</li>
 *   <li>其他兼容OpenAI格式的API</li>
 * </ul>
 * 
 * <p>特点：同步API，立即返回结果
 * 
 * @author 1818AI
 * @since 2025-10-20
 */
@Slf4j
@Service("openAIProvider")
@RequiredArgsConstructor
public class OpenAIProviderImpl implements AIProvider {

    private final ThirdPartyApiService thirdPartyApiService;
    
    private static final Pattern URL_PATTERN = Pattern.compile("!\\[.*?\\]\\((https?://[^)]+)\\)");

    @Override
    public ProviderTaskResponse submitTask(ProviderTaskRequest request) {
        log.info("OpenAI Provider - 提交任务，模型: {}", request.getModelName());
        
        try {
            // 调用现有的ThirdPartyApiService
            ApiResponse apiResponse = thirdPartyApiService.executeGenerationForTask(
                buildAiTaskFromRequest(request)
            );
            
            // 从响应中提取URL
            String resultUrl = extractUrlFromResponse(apiResponse);
            
            if (resultUrl != null) {
                log.info("OpenAI Provider - 任务成功，结果URL: {}", resultUrl);
                
                return ProviderTaskResponse.builder()
                        .providerTaskId(null)  // OpenAI是同步的，不需要taskId
                        .status(ProviderTaskResponse.TaskSubmitStatus.COMPLETED)
                        .resultUrl(resultUrl)
                        .rawResponse(buildRawResponse(apiResponse))
                        .build();
            } else {
                log.error("OpenAI Provider - 无法从响应中提取URL");
                return ProviderTaskResponse.builder()
                        .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                        .errorMessage("无法从API响应中提取结果URL")
                        .rawResponse(buildRawResponse(apiResponse))
                        .build();
            }
            
        } catch (Exception e) {
            log.error("OpenAI Provider - 任务失败: {}", e.getMessage(), e);
            return ProviderTaskResponse.builder()
                    .status(ProviderTaskResponse.TaskSubmitStatus.FAILED)
                    .errorMessage("API调用失败: " + e.getMessage())
                    .build();
        }
    }

    @Override
    public ProviderTaskStatus queryTaskStatus(String providerTaskId) {
        // OpenAI是同步API，不需要查询状态
        throw new UnsupportedOperationException("OpenAI是同步API，不支持查询状态");
    }

    @Override
    public ProviderTaskResult getTaskResult(String providerTaskId) {
        // OpenAI是同步API，不需要获取结果
        throw new UnsupportedOperationException("OpenAI是同步API，不支持异步获取结果");
    }

    @Override
    public String getProviderName() {
        return "openai";
    }

    @Override
    public boolean isAsyncProvider() {
        return false;  // OpenAI是同步API
    }

    /**
     * 从ProviderTaskRequest构建AiTask对象
     */
    private AiTask buildAiTaskFromRequest(ProviderTaskRequest request) {
        AiTask task = new AiTask();
        task.setModelName(request.getModelName());
        task.setPrompt(request.getPrompt());
        task.setImageUrl(request.getImageUrl());
        task.setImageBase64(request.getImageBase64());
        task.setAspectRatio(request.getAspectRatio());
        return task;
    }

    /**
     * 从API响应中提取URL
     */
    private String extractUrlFromResponse(ApiResponse response) {
        if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
            return null;
        }

        String content = response.getChoices().get(0).getMessage().getContent();
        if (content == null || content.trim().isEmpty()) {
            return null;
        }

        // 使用正则提取Markdown格式的图片链接
        Matcher matcher = URL_PATTERN.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }

        return null;
    }

    /**
     * 构建原始响应Map
     */
    private Map<String, Object> buildRawResponse(ApiResponse response) {
        Map<String, Object> rawResponse = new HashMap<>();
        if (response != null) {
            rawResponse.put("id", response.getId());
            rawResponse.put("model", response.getModel());
            rawResponse.put("created", response.getCreated());
            if (response.getChoices() != null && !response.getChoices().isEmpty()) {
                rawResponse.put("content", response.getChoices().get(0).getMessage().getContent());
            }
        }
        return rawResponse;
    }
}

