package com.moka.gdtauto.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.moka.gdtauto.GdtAutoApplication;
import com.moka.gdtauto.client.TencentAdsApiClientFactory;
import com.tencent.ads.model.v3.VideosAddResponseData;
import com.tencent.ads.v3.TencentAds;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 腾讯广告视频上传测试
 * https://developers.e.qq.com/v3.0/docs/api/videos/add
 * @author moka
 * @since 2026-02-06
 */
@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
class TencentVideoAddTest {

    @Autowired
    private TencentAdsApiClientFactory clientFactory;

    private static final Long ORG_ACCOUNT_ID = 33453856L;
    private static final Long TEST_ACCOUNT_ID = 69781948L;
    private static final String TEST_JOB_NUMBER = "12458";

    @Test
    @DisplayName("测试上传视频文件")
    void testUploadVideoFile() {
        System.out.println("\n========================================");
        System.out.println("开始上传视频文件");
        System.out.println("账户ID: " + TEST_ACCOUNT_ID);
        System.out.println("========================================\n");

        try {
            // 获取TencentAds实例
            TencentAds tencentAds = clientFactory.getTencentAds(TEST_JOB_NUMBER, ORG_ACCOUNT_ID);
            tencentAds.setDebug(true);

            // 视频文件路径（请替换为实际视频路径）
            String videoPath = "/Users/pudongliang/moka_workspace/gdt-auto/test.mp4";
            File videoFile = new File(videoPath);
            
            if (!videoFile.exists()) {
                System.err.println("❌ 视频文件不存在: " + videoPath);
                System.err.println("请修改 videoPath 为实际的视频文件路径");
                System.err.println("支持的格式: mp4、mov、avi，最大支持 100M");
                return;
            }

            // 检查文件大小
            long fileSizeInMB = videoFile.length() / (1024 * 1024);
            if (fileSizeInMB > 100) {
                System.err.println("❌ 视频文件过大: " + fileSizeInMB + "MB，超过 100MB 限制");
                return;
            }

            // 计算视频MD5签名
            String signature = calculateMD5(videoFile);
            System.out.println("视频MD5签名: " + signature);
            System.out.println("视频文件大小: " + fileSizeInMB + "MB");

            String description = "测试上传视频-" + System.currentTimeMillis();
            
            // 输出请求参数
            System.out.println("\n========== 请求参数 ==========");
            System.out.println("账户ID: " + TEST_ACCOUNT_ID);
            System.out.println("签名: " + signature);
            System.out.println("文件路径: " + videoPath);
            System.out.println("文件大小: " + fileSizeInMB + "MB");
            System.out.println("描述: " + description);
            System.out.println("========================================\n");

            // 调用上传接口
            System.out.println("正在调用腾讯广告上传视频API...");
            VideosAddResponseData response = tencentAds.videos()
                .videosAdd(
                    videoFile,           // videoFile
                    signature,           // signature
                    TEST_ACCOUNT_ID,     // accountId
                    null,                // organizationId
                    description,         // description
                    null                 // adcreativeTemplateId
                );

            // 输出响应结果
            System.out.println("\n========== API返回结果 ==========");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(response));
            System.out.println("========================================\n");

            // 输出摘要信息
            if (response != null) {
                System.out.println("✅ 成功上传视频");
                System.out.println("📊 视频ID: " + response.getVideoId());
                if (response.getCoverImageId() != null) {
                    System.out.println("📊 封面图片ID: " + response.getCoverImageId());
                }
            } else {
                System.out.println("⚠️  返回结果为空");
            }

        } catch (Exception e) {
            System.err.println("\n❌ API调用失败");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("测试失败", e);
        }
    }

    @Test
    @DisplayName("测试上传视频文件-指定创意形式")
    void testUploadVideoWithTemplate() {
        System.out.println("\n========================================");
        System.out.println("开始上传视频文件(指定创意形式)");
        System.out.println("账户ID: " + TEST_ACCOUNT_ID);
        System.out.println("========================================\n");

        try {
            // 获取TencentAds实例
            TencentAds tencentAds = clientFactory.getTencentAds(TEST_JOB_NUMBER, ORG_ACCOUNT_ID);
            tencentAds.setDebug(true);

            // 视频文件路径（请替换为实际视频路径）
            String videoPath = "/path/to/your/video.mp4";
            File videoFile = new File(videoPath);
            
            if (!videoFile.exists()) {
                System.err.println("❌ 视频文件不存在: " + videoPath);
                System.err.println("请修改 videoPath 为实际的视频文件路径");
                return;
            }

            // 计算视频MD5签名
            String signature = calculateMD5(videoFile);
            String description = "测试上传视频-指定创意形式-" + System.currentTimeMillis();
            
            // 创意形式ID（请根据实际情况替换）
            Long adcreativeTemplateId = 1234L;
            
            // 输出请求参数
            System.out.println("\n========== 请求参数 ==========");
            System.out.println("账户ID: " + TEST_ACCOUNT_ID);
            System.out.println("签名: " + signature);
            System.out.println("文件路径: " + videoPath);
            System.out.println("描述: " + description);
            System.out.println("创意形式ID: " + adcreativeTemplateId);
            System.out.println("========================================\n");

            // 调用上传接口
            System.out.println("正在调用腾讯广告上传视频API...");
            VideosAddResponseData response = tencentAds.videos()
                .videosAdd(
                    videoFile,              // videoFile
                    signature,              // signature
                    TEST_ACCOUNT_ID,        // accountId
                    null,                   // organizationId
                    description,            // description
                    adcreativeTemplateId    // adcreativeTemplateId
                );

            // 输出响应结果
            System.out.println("\n========== API返回结果 ==========");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(response));
            System.out.println("========================================\n");

            // 输出摘要信息
            if (response != null) {
                System.out.println("✅ 成功上传视频");
                System.out.println("📊 视频ID: " + response.getVideoId());
                if (response.getCoverImageId() != null) {
                    System.out.println("📊 封面图片ID: " + response.getCoverImageId());
                }
            } else {
                System.out.println("⚠️  返回结果为空");
            }

        } catch (Exception e) {
            System.err.println("\n❌ API调用失败");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("测试失败", e);
        }
    }

    @Test
    @DisplayName("测试上传视频文件-使用组织ID")
    void testUploadVideoWithOrganizationId() {
        System.out.println("\n========================================");
        System.out.println("开始上传视频文件(使用组织ID)");
        System.out.println("组织ID: " + ORG_ACCOUNT_ID);
        System.out.println("========================================\n");

        try {
            // 获取TencentAds实例
            TencentAds tencentAds = clientFactory.getTencentAds(TEST_JOB_NUMBER, ORG_ACCOUNT_ID);
            tencentAds.setDebug(true);

            // 视频文件路径（请替换为实际视频路径）
            String videoPath = "/path/to/your/video.mp4";
            File videoFile = new File(videoPath);
            
            if (!videoFile.exists()) {
                System.err.println("❌ 视频文件不存在: " + videoPath);
                System.err.println("请修改 videoPath 为实际的视频文件路径");
                return;
            }

            // 计算视频MD5签名
            String signature = calculateMD5(videoFile);
            String description = "测试上传视频-组织ID-" + System.currentTimeMillis();
            
            // 输出请求参数
            System.out.println("\n========== 请求参数 ==========");
            System.out.println("组织ID: " + ORG_ACCOUNT_ID);
            System.out.println("签名: " + signature);
            System.out.println("文件路径: " + videoPath);
            System.out.println("描述: " + description);
            System.out.println("========================================\n");

            // 调用上传接口
            System.out.println("正在调用腾讯广告上传视频API...");
            VideosAddResponseData response = tencentAds.videos()
                .videosAdd(
                    videoFile,           // videoFile
                    signature,           // signature
                    null,                // accountId
                    ORG_ACCOUNT_ID,      // organizationId
                    description,         // description
                    null                 // adcreativeTemplateId
                );

            // 输出响应结果
            System.out.println("\n========== API返回结果 ==========");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(response));
            System.out.println("========================================\n");

            // 输出摘要信息
            if (response != null) {
                System.out.println("✅ 成功上传视频");
                System.out.println("📊 视频ID: " + response.getVideoId());
                if (response.getCoverImageId() != null) {
                    System.out.println("📊 封面图片ID: " + response.getCoverImageId());
                }
            } else {
                System.out.println("⚠️  返回结果为空");
            }

        } catch (Exception e) {
            System.err.println("\n❌ API调用失败");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("测试失败", e);
        }
    }

    /**
     * 计算文件的MD5签名
     */
    private String calculateMD5(File file) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        String hashtext = bigInt.toString(16);
        // 补齐前导0
        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }
        return hashtext;
    }
}
