package com.dora.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.dora.config.OssConfig;
import com.dora.util.OssUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.net.URL;

/**
 * 结果文件转存服务
 * 将第三方AI服务提供的临时URL文件转存到自己的OSS
 * 
 * @author 1818AI
 * @since 2025-10-24
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ResultFileTransferService {

    private final OSS ossClient;
    private final OssConfig ossConfig;
    private final RestTemplate restTemplate;

    /**
     * 将远程URL的文件转存到OSS
     * 
     * @param sourceUrl 源文件URL
     * @param userId 用户ID
     * @param taskNo 任务编号
     * @return OSS永久URL，如果失败返回原URL
     */
    public String transferToOss(String sourceUrl, Long userId, String taskNo) {
        if (sourceUrl == null || sourceUrl.trim().isEmpty()) {
            log.warn("源URL为空，跳过转存");
            return sourceUrl;
        }

        try {
            log.info("开始转存文件到OSS - 任务: {}, 源URL: {}", taskNo, sourceUrl);

            // 1. 从URL下载文件
            InputStream inputStream = downloadFile(sourceUrl);
            if (inputStream == null) {
                log.error("下载文件失败，返回原URL - 任务: {}", taskNo);
                return sourceUrl;
            }

            // 2. 生成OSS对象键
            String fileExtension = extractFileExtension(sourceUrl);
            String uniqueFileName = generateResultFileName(userId, taskNo, fileExtension);
            String objectKey = ossConfig.getUserImgFolder() + "/" + uniqueFileName;

            // 3. 设置对象元数据
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(getContentTypeFromExtension(fileExtension));

            // 4. 上传到OSS
            ossClient.putObject(ossConfig.getBucketName(), objectKey, inputStream, metadata);
            
            // 5. 生成永久URL
            String permanentUrl = generatePermanentUrl(objectKey);
            
            log.info("文件转存成功 - 任务: {}, OSS URL: {}", taskNo, permanentUrl);
            return permanentUrl;

        } catch (Exception e) {
            log.error("转存文件到OSS失败 - 任务: {}, 错误: {}", taskNo, e.getMessage(), e);
            return sourceUrl; // 失败时返回原URL，确保业务不中断
        }
    }

    /**
     * 下载远程文件
     */
    private InputStream downloadFile(String url) {
        try {
            ResponseEntity<byte[]> response = restTemplate.exchange(
                url, 
                HttpMethod.GET, 
                null, 
                byte[].class
            );
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return new java.io.ByteArrayInputStream(response.getBody());
            }
            
            log.error("下载文件失败，HTTP状态: {}", response.getStatusCode());
            return null;
            
        } catch (Exception e) {
            log.error("下载文件异常: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 从URL提取文件扩展名
     */
    private String extractFileExtension(String url) {
        try {
            URL urlObj = new URL(url);
            String path = urlObj.getPath();
            
            if (path != null && path.contains(".")) {
                String ext = path.substring(path.lastIndexOf("."));
                // 移除查询参数
                if (ext.contains("?")) {
                    ext = ext.substring(0, ext.indexOf("?"));
                }
                return ext;
            }
            
            // 默认为mp4（大多数视频结果）
            return ".mp4";
            
        } catch (Exception e) {
            log.warn("提取文件扩展名失败，使用默认值: {}", e.getMessage());
            return ".mp4";
        }
    }

    /**
     * 生成结果文件名
     */
    private String generateResultFileName(Long userId, String taskNo, String extension) {
        String timestamp = String.valueOf(System.currentTimeMillis());
        return userId + "_" + taskNo + "_" + timestamp + extension;
    }

    /**
     * 根据扩展名获取Content-Type
     */
    private String getContentTypeFromExtension(String extension) {
        if (extension == null) {
            return "application/octet-stream";
        }
        
        switch (extension.toLowerCase()) {
            case ".mp4":
                return "video/mp4";
            case ".mov":
                return "video/quicktime";
            case ".avi":
                return "video/x-msvideo";
            case ".webm":
                return "video/webm";
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            case ".gif":
                return "image/gif";
            case ".webp":
                return "image/webp";
            default:
                return OssUtil.getContentType("file" + extension);
        }
    }

    /**
     * 生成OSS永久URL
     */
    private String generatePermanentUrl(String objectKey) {
        // 使用OSS的公共访问域名或CDN域名
        return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint().replace("https://", "").replace("http://", "") + "/" + objectKey;
    }
}

