// 编解码测试程序
#include "code/base/logger.h"
#include "code/codec/codec_video_encoder.h"
#include "code/codec/codec_audio_encoder.h"
#include <iostream>
#include <chrono>
#include <thread>

using namespace av;
using namespace av::codec;

int main() {
    AV_LOGGER_INFO("=== AV编解码测试 ===");
    
    // 初始化日志系统
    Logger::initialize("codec_test_log.txt", LogLevel::DEBUG, false, true);

    // 初始化FFmpeg
    ffmpeg_utils::initializeFFmpeg();
    
    try {
        // 1. 测试视频编码器支持
        AV_LOGGER_INFO("1. 测试视频编码器支持...");
        auto videoEncoders = VideoEncoder::getSupportedEncoders();
        AV_LOGGER_INFOF("支持的视频编码器数量: {}", videoEncoders.size());
        
        for (const auto& encoder : videoEncoders) {
            AV_LOGGER_INFOF("  - {} (硬件: {})", encoder, 
                         VideoEncoder::isHardwareEncoder(encoder) ? "是" : "否");
        }
        
        std::string recommendedVideo = VideoEncoder::getRecommendedEncoder();
        AV_LOGGER_INFOF("推荐的视频编码器: {}", recommendedVideo);
        
        // 2. 测试音频编码器支持
        AV_LOGGER_INFO("2. 测试音频编码器支持...");
        auto audioEncoders = AudioEncoder::getSupportedEncoders();
        AV_LOGGER_INFOF("支持的音频编码器数量: {}", audioEncoders.size());
        
        for (const auto& encoder : audioEncoders) {
            AV_LOGGER_INFOF("  - {}", encoder);
        }
        
        std::string recommendedAudio = AudioEncoder::getRecommendedEncoder();
        AV_LOGGER_INFOF("推荐的音频编码器: {}", recommendedAudio);
        
        // 3. 测试视频编码器创建和配置
        AV_LOGGER_INFO("3. 测试视频编码器创建...");
        if (!recommendedVideo.empty()) {
            auto videoEncoder = VideoEncoderFactory::create(recommendedVideo);
            if (videoEncoder) {
                AV_LOGGER_INFO("视频编码器创建成功");
                
                // 配置编码器参数
                VideoEncoderParams videoParams;
                videoParams.codecName = recommendedVideo;
                videoParams.width = 1280;
                videoParams.height = 720;
                videoParams.fps = 30;
                videoParams.bitRate = 2000000;
                videoParams.lowLatency = true;
                videoParams.hardwareAccel = true;  // 启用硬件加速
                
                AVResult result = videoEncoder->open(videoParams);
                if (result == AVResult::SUCCESS) {
                    AV_LOGGER_INFO("视频编码器打开成功");
                    
                    // 测试编码器状态
                    AV_LOGGER_INFOF("编码器状态: {}", static_cast<int>(videoEncoder->getState()));
                    AV_LOGGER_INFOF("是否已打开: {}", videoEncoder->isOpened() ? "是" : "否");
                    
                    videoEncoder->close();
                    AV_LOGGER_INFO("视频编码器已关闭");
                } else {
                    AV_LOGGER_ERRORF("硬件视频编码器打开失败: {}", static_cast<int>(result));
                    
                    // 尝试软件编码器
                    AV_LOGGER_INFO("尝试使用软件编码器...");
                    videoParams.hardwareAccel = false;
                    videoParams.codecName = "libx264";
                    
                    auto softwareEncoder = VideoEncoderFactory::create("libx264");
                    if (softwareEncoder) {
                        AVResult softResult = softwareEncoder->open(videoParams);
                        if (softResult == AVResult::SUCCESS) {
                            AV_LOGGER_INFO("软件视频编码器打开成功");
                            softwareEncoder->close();
                            AV_LOGGER_INFO("软件视频编码器已关闭");
                        } else {
                            AV_LOGGER_ERRORF("软件视频编码器打开失败: {}", static_cast<int>(softResult));
                        }
                    }
                }
            } else {
                AV_LOGGER_ERROR("视频编码器创建失败");
            }
        } else {
            AV_LOGGER_WARNING("没有可用的视频编码器");
        }
        
        // 4. 测试音频编码器创建和配置
        AV_LOGGER_INFO("4. 测试音频编码器创建...");
        if (!recommendedAudio.empty()) {
            auto audioEncoder = AudioEncoderFactory::create(recommendedAudio);
            if (audioEncoder) {
                AV_LOGGER_INFO("音频编码器创建成功");
                
                // 配置编码器参数
                AudioEncoderParams audioParams;
                audioParams.codecName = recommendedAudio;
                audioParams.sampleRate = 44100;
                audioParams.channels = 2;
                audioParams.bitRate = 128000;
                av_channel_layout_default(&audioParams.channelLayout, 2);
                
                AVResult result = audioEncoder->open(audioParams);
                if (result == AVResult::SUCCESS) {
                    AV_LOGGER_INFO("音频编码器打开成功");
                    
                    // 测试编码器状态
                    AV_LOGGER_INFOF("编码器状态: {}", static_cast<int>(audioEncoder->getState()));
                    AV_LOGGER_INFOF("是否已打开: {}", audioEncoder->isOpened() ? "是" : "否");
                    
                    audioEncoder->close();
                    AV_LOGGER_INFO("音频编码器已关闭");
                } else {
                    AV_LOGGER_ERRORF("音频编码器打开失败: {}", static_cast<int>(result));
                }
            } else {
                AV_LOGGER_ERROR("音频编码器创建失败");
            }
        } else {
            AV_LOGGER_WARNING("没有可用的音频编码器");
        }
        
        // 5. 测试编码器工厂
        AV_LOGGER_INFO("5. 测试编码器工厂...");
        
        // 测试最佳视频编码器
        auto bestVideoEncoder = VideoEncoderFactory::createBest(true);
        if (bestVideoEncoder) {
            AV_LOGGER_INFO("最佳视频编码器创建成功（硬件优先）");
        }
        
        auto softwareVideoEncoder = VideoEncoderFactory::createBest(false);
        if (softwareVideoEncoder) {
            AV_LOGGER_INFO("最佳视频编码器创建成功（软件优先）");
        }
        
        // 测试最佳音频编码器
        auto bestAudioEncoder = AudioEncoderFactory::createBest();
        if (bestAudioEncoder) {
            AV_LOGGER_INFO("最佳音频编码器创建成功");
        }
        
        // 测试无损音频编码器
        auto losslessAudioEncoder = AudioEncoderFactory::createLossless();
        if (losslessAudioEncoder) {
            AV_LOGGER_INFO("无损音频编码器创建成功");
        }
        
        // 6. 测试编码器能力查询
        AV_LOGGER_INFO("6. 测试编码器能力查询...");
        
        // 测试音频编码器能力
        if (!recommendedAudio.empty()) {
            bool supportsFLTP = AudioEncoder::isSampleFormatSupported(recommendedAudio, AV_SAMPLE_FMT_FLTP);
            bool supports44100 = AudioEncoder::isSampleRateSupported(recommendedAudio, 44100);
            
            AVChannelLayout stereoLayout = AV_CHANNEL_LAYOUT_STEREO;
            bool supportsStereo = AudioEncoder::isChannelLayoutSupported(recommendedAudio, stereoLayout);
            
            AV_LOGGER_INFOF("编码器 {} 支持:", recommendedAudio);
            AV_LOGGER_INFOF("  - FLTP格式: {}", supportsFLTP ? "是" : "否");
            AV_LOGGER_INFOF("  - 44100Hz: {}", supports44100 ? "是" : "否");
            AV_LOGGER_INFOF("  - 立体声: {}", supportsStereo ? "是" : "否");
        }
        
        // 7. 测试编码器统计信息
        AV_LOGGER_INFO("7. 测试编码器统计信息...");
        if (!recommendedVideo.empty()) {
            auto encoder = VideoEncoderFactory::create(recommendedVideo);
            if (encoder) {
                const auto& stats = encoder->getStatistics();
                AV_LOGGER_INFOF("编码器统计信息:");
                AV_LOGGER_INFOF("  - 处理帧数: {}", stats.processedFrames);
                AV_LOGGER_INFOF("  - 丢弃帧数: {}", stats.droppedFrames);
                AV_LOGGER_INFOF("  - 错误次数: {}", stats.errorCount);
                AV_LOGGER_INFOF("  - 平均处理时间: {:.2f}ms", stats.avgProcessTime);
                AV_LOGGER_INFOF("  - 总字节数: {}", stats.totalBytes);
            }
        }

        AV_LOGGER_INFO("=== 所有编解码测试完成 ===");
        AV_LOGGER_INFO("测试完成，请查看 codec_test_log.txt 文件");
        
    } catch (const std::exception& e) {
        AV_LOGGER_ERRORF("测试过程中发生异常: {}", e.what());
        AV_LOGGER_ERRORF("测试失败: {}", e.what());
        return 1;
    }
    
    // 清理FFmpeg
    ffmpeg_utils::cleanupFFmpeg();
    
    return 0;
}
