package com.wzj.soopin.content.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

/**
 * 腾讯云工具类
 */
@Slf4j
@Component
public class TencentCloudUtil {

    @Autowired
    private TencentCloudProperties properties;
    /**
     * 获取VOD客户端实例
     *
     * @return VodClient实例
     */
    public VodClient getVodClient() {
        // 从配置中获取值
        String secretId = properties.getSecretId();
        String secretKey = properties.getSecretKey();
        String region = properties.getRegion();
        String appId = properties.getVod().getAppId();

        // 详细的配置检查日志
        log.info("开始初始化腾讯云 VOD 客户端");
        log.info("配置检查 - SecretId长度: {}, SecretKey长度: {}, Region: {}, AppId: {}",
            secretId != null ? secretId.length() : 0,
            secretKey != null ? secretKey.length() : 0,
            region,
            appId);

        // 检查密钥格式
        if (secretId == null || secretId.isEmpty()) {
            throw new IllegalArgumentException("SecretId 不能为空");
        }
        if (secretKey == null || secretKey.isEmpty()) {
            throw new IllegalArgumentException("SecretKey 不能为空");
        }
        if (region == null || region.isEmpty()) {
            throw new IllegalArgumentException("Region 不能为空");
        }

        // 检查密钥格式
        if (secretId.contains(" ")) {
            log.warn("SecretId 包含空格，这可能导致签名验证失败");
            secretId = secretId.trim();
        }
        if (secretKey.contains(" ")) {
            log.warn("SecretKey 包含空格，这可能导致签名验证失败");
            secretKey = secretKey.trim();
        }

        // 输出服务器时间和时区信息
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        LocalDateTime utcNow = LocalDateTime.now(ZoneId.of("UTC"));
        log.info("服务器时间 - 本地: {}, UTC: {}, 时区: {}",
            now.format(DateTimeFormatter.ISO_DATE_TIME),
            utcNow.format(DateTimeFormatter.ISO_DATE_TIME),
            ZoneId.systemDefault().getId());

        // 检查密钥编码
        try {
            byte[] secretIdBytes = secretId.getBytes(StandardCharsets.UTF_8);
            byte[] secretKeyBytes = secretKey.getBytes(StandardCharsets.UTF_8);

            // 检查密钥格式
            if (secretIdBytes.length != 36) {
                log.warn("SecretId 长度异常: {}, 预期长度: 36", secretIdBytes.length);
            }
            if (secretKeyBytes.length != 64) {
                log.warn("SecretKey 长度异常: {}, 预期长度: 64", secretKeyBytes.length);
            }

            // 检查密钥字符
            if (!secretId.matches("^[A-Za-z0-9]+$")) {
                log.warn("SecretId 包含非字母数字字符");
            }
            if (!secretKey.matches("^[A-Za-z0-9]+$")) {
                log.warn("SecretKey 包含非字母数字字符");
            }

            log.info("密钥编码检查 - SecretId UTF-8长度: {}, Base64: {}",
                secretIdBytes.length,
                Base64.getEncoder().encodeToString(secretIdBytes));
            log.info("密钥编码检查 - SecretKey UTF-8长度: {}, Base64: {}",
                secretKeyBytes.length,
                Base64.getEncoder().encodeToString(secretKeyBytes));
        } catch (Exception e) {
            log.error("密钥编码检查失败", e);
            throw new IllegalArgumentException("密钥编码检查失败: " + e.getMessage());
        }

        try {
            // **添加日志，确认Credential和VodClient实例化前使用的实际密钥和AppId**
            log.info("实例化 Credential 和 VodClient - SecretId: {}, SecretKey长度: {}, Region: {}, AppId: {}",
                secretId != null ? secretId.substring(0, 4) + "****" : "null", // 隐藏部分密钥
                secretKey != null ? secretKey.length() : 0,
                region,
                appId);

            // 实例化一个认证对象
            Credential cred = new Credential(secretId, secretKey);

            // 实例化要请求产品的client对象
            VodClient client = new VodClient(cred, region);
            log.info("腾讯云 VOD 客户端初始化成功 (地域参数: {})", region);
            return client;
        } catch (Exception e) {
            log.error("初始化腾讯云 VOD 客户端失败", e);
            throw new RuntimeException("初始化腾讯云 VOD 客户端失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取密钥ID
     *
     * @return 密钥ID
     */
    public String getSecretId() {
        return properties.getSecretId();
    }

    /**
     * 获取密钥Key
     *
     * @return 密钥Key
     */
    public String getSecretKey() {
        return properties.getSecretKey();
    }

    /**
     * 获取应用ID
     *
     * @return 应用ID
     */
    public String getAppId() {
        return properties.getVod().getAppId();
    }

    /**
     * 获取视频播放地址
     *
     * @param fileId 视频文件ID
     * @return 播放地址
     */
    public String getVideoPlayUrl(String fileId) {
        // TODO: 实现获取视频播放地址的逻辑
        return null;
    }

    /**
     * 获取视频封面地址
     *
     * @param fileId 视频文件ID
     * @return 封面地址
     */
    public String getVideoCoverUrl(String fileId) {
        // TODO: 实现获取视频封面地址的逻辑
        return null;
    }
}
