#include "code/base/logger.h"
#include "code/base/types.h"
#include "code/codec/codec_audio_decoder.h"
#include "code/codec/codec_video_decoder.h"
#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include <vector>

extern "C" {
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/avutil.h>
}

using namespace av;
using namespace av::codec;

class DecoderTester {
public:
    DecoderTester() {
        // 初始化FFmpeg
        av_log_set_level(AV_LOG_INFO);
        
        // 初始化日志系统
        av::Logger::instance().setLevel(av::LogLevel::DEBUG);
        av::Logger::instance().addOutput(std::make_unique<av::QtOutput>());

        std::cout << "=== AV解码器测试程序 ===" << std::endl;
        std::cout << "FFmpeg版本: " << av_version_info() << std::endl;
    }
    
    ~DecoderTester() {
        // 日志系统自动清理
    }
    
    // 测试视频解码器基本功能
    bool testVideoDecoderBasic() {
        std::cout << "\n--- 测试视频解码器基本功能 ---" << std::endl;
        
        try {
            // 创建解码器
            auto decoder = std::make_unique<VideoDecoder>();
            
            // 测试支持的解码器列表
            auto supportedDecoders = VideoDecoder::getSupportedDecoders();
            std::cout << "支持的视频解码器数量: " << supportedDecoders.size() << std::endl;
            
            for (const auto& codecName : supportedDecoders) {
                std::cout << "  - " << codecName;
                if (VideoDecoder::isHardwareDecoder(codecName)) {
                    std::cout << " (硬件加速)";
                }
                std::cout << std::endl;
            }
            
            // 测试H.264解码器初始化
            VideoDecoderParams params;
            params.codecName = "h264";
            params.pixelFormat = AV_PIX_FMT_YUV420P;
            params.hardwareAccel = false; // 先测试软件解码
            params.threadCount = 4;
            
            ErrorCode result = decoder->open(params);
            if (result != ErrorCode::SUCCESS) {
                std::cerr << "打开H.264解码器失败: " << static_cast<int>(result) << std::endl;
                return false;
            }
            
            std::cout << "H.264解码器初始化成功" << std::endl;
            std::cout << "解码器名称: " << decoder->getDecoderName() << std::endl;
            std::cout << "是否硬件解码器: " << (decoder->isHardwareDecoder() ? "是" : "否") << std::endl;
            
            // 测试统计信息
            auto stats = decoder->getStats();
            std::cout << "初始统计信息:" << std::endl;
            std::cout << "  解码帧数: " << stats.decodedFrames << std::endl;
            std::cout << "  丢弃帧数: " << stats.droppedFrames << std::endl;
            std::cout << "  错误次数: " << stats.errorCount << std::endl;
            
            decoder->close();
            std::cout << "视频解码器基本功能测试通过" << std::endl;
            return true;
            
        } catch (const std::exception& e) {
            std::cerr << "视频解码器测试异常: " << e.what() << std::endl;
            return false;
        }
    }
    
    // 测试音频解码器基本功能
    bool testAudioDecoderBasic() {
        std::cout << "\n--- 测试音频解码器基本功能 ---" << std::endl;
        
        try {
            // 创建解码器
            auto decoder = std::make_unique<AudioDecoder>();
            
            // 测试AAC解码器初始化
            AudioDecoderParams params;
            params.codecName = "aac";
            params.sampleRate = 44100;
            params.channels = 2;
            params.sampleFormat = AV_SAMPLE_FMT_S16;
             params.enableResampling = true;
            
            ErrorCode result = decoder->open(params);
            if (result != ErrorCode::SUCCESS) {
                std::cerr << "打开AAC解码器失败: " << static_cast<int>(result) << std::endl;
                return false;
            }
            
            std::cout << "AAC解码器初始化成功" << std::endl;
            std::cout << "解码器名称: " << decoder->getDecoderName() << std::endl;
            std::cout << "是否启用重采样: " << (decoder->isResamplingEnabled() ? "是" : "否") << std::endl;
            
            // 测试统计信息
            auto stats = decoder->getStats();
            std::cout << "初始统计信息:" << std::endl;
            std::cout << "  解码帧数: " << stats.decodedFrames << std::endl;
            std::cout << "  重采样帧数: " << stats.resampledFrames << std::endl;
            std::cout << "  错误次数: " << stats.errorCount << std::endl;
            
            decoder->close();
            std::cout << "音频解码器基本功能测试通过" << std::endl;
            return true;
            
        } catch (const std::exception& e) {
            std::cerr << "音频解码器测试异常: " << e.what() << std::endl;
            return false;
        }
    }
    
    // 测试硬件加速解码器
    bool testHardwareDecoder() {
        std::cout << "\n--- 测试硬件加速解码器 ---" << std::endl;
        
        try {
            // 获取推荐的硬件解码器
            std::string recommendedDecoder = VideoDecoder::getRecommendedDecoder();
            if (recommendedDecoder.empty()) {
                std::cout << "未找到推荐的硬件解码器，跳过测试" << std::endl;
                return true;
            }
            
            std::cout << "推荐的解码器: " << recommendedDecoder << std::endl;
            
            auto decoder = std::make_unique<VideoDecoder>();
            
            VideoDecoderParams params;
            params.codecName = recommendedDecoder;
            params.hardwareAccel = true;
            params.lowLatency = true;
            
            ErrorCode result = decoder->open(params);
            if (result != ErrorCode::SUCCESS) {
                std::cout << "硬件解码器打开失败，可能不支持: " << static_cast<int>(result) << std::endl;
                return true; // 不算失败，因为硬件支持因环境而异
            }
            
            std::cout << "硬件解码器测试成功" << std::endl;
            std::cout << "解码器名称: " << decoder->getDecoderName() << std::endl;
            std::cout << "是否硬件解码器: " << (decoder->isHardwareDecoder() ? "是" : "否") << std::endl;
            
            decoder->close();
            return true;
            
        } catch (const std::exception& e) {
            std::cout << "硬件解码器测试异常（可能正常）: " << e.what() << std::endl;
            return true; // 硬件相关异常不算失败
        }
    }
    
    // 测试解码器工厂
    bool testDecoderFactory() {
        std::cout << "\n--- 测试解码器工厂 ---" << std::endl;
        
        try {
            // 测试创建最佳解码器
            auto bestDecoder = VideoDecoder::VideoDecoderFactory::createBest(false); // 优先软件解码
            if (!bestDecoder) {
                std::cerr << "创建最佳解码器失败" << std::endl;
                return false;
            }
            
            std::cout << "成功创建最佳软件解码器" << std::endl;
            
            // 测试创建指定解码器
            auto h264Decoder = VideoDecoder::VideoDecoderFactory::create("h264");
            if (!h264Decoder) {
                std::cerr << "创建H.264解码器失败" << std::endl;
                return false;
            }
            
            std::cout << "成功创建H.264解码器" << std::endl;
            
            // 测试创建硬件解码器
            auto hwDecoder = VideoDecoder::VideoDecoderFactory::createBest(true); // 优先硬件解码
            if (hwDecoder) {
                std::cout << "成功创建硬件解码器" << std::endl;
            } else {
                std::cout << "硬件解码器不可用（正常）" << std::endl;
            }
            
            std::cout << "解码器工厂测试通过" << std::endl;
            return true;
            
        } catch (const std::exception& e) {
            std::cerr << "解码器工厂测试异常: " << e.what() << std::endl;
            return false;
        }
    }
    
    // 测试解码器状态管理
    bool testDecoderStateManagement() {
        std::cout << "\n--- 测试解码器状态管理 ---" << std::endl;
        
        try {
            auto decoder = std::make_unique<VideoDecoder>();
            
            // 测试初始状态
            if (decoder->getState() != CodecState::IDLE) {
                std::cerr << "初始状态错误" << std::endl;
                return false;
            }
            
            // 测试打开
            VideoDecoderParams params;
            params.codecName = "h264";
            
            ErrorCode result = decoder->open(params);
            if (result != ErrorCode::SUCCESS) {
                std::cerr << "打开失败" << std::endl;
                return false;
            }
            
            if (decoder->getState() != CodecState::OPENED) {
                std::cerr << "打开后状态错误" << std::endl;
                return false;
            }
            
            // 测试重置
            result = decoder->reset();
            if (result != ErrorCode::SUCCESS) {
                std::cerr << "重置失败" << std::endl;
                return false;
            }
            
            if (decoder->getState() != CodecState::OPENED) {
                std::cerr << "重置后状态错误" << std::endl;
                return false;
            }
            
            // 测试关闭
            decoder->close();
            
            if (decoder->getState() != CodecState::IDLE) {
                std::cerr << "关闭后状态错误" << std::endl;
                return false;
            }
            
            std::cout << "解码器状态管理测试通过" << std::endl;
            return true;
            
        } catch (const std::exception& e) {
            std::cerr << "解码器状态管理测试异常: " << e.what() << std::endl;
            return false;
        }
    }
    
    // 测试错误处理
    bool testErrorHandling() {
        std::cout << "\n--- 测试错误处理 ---" << std::endl;
        
        try {
            auto decoder = std::make_unique<VideoDecoder>();
            
            // 测试无效参数
            VideoDecoderParams invalidParams;
            invalidParams.codecName = ""; // 空名称
            
            ErrorCode result = decoder->open(invalidParams);
            if (result == ErrorCode::SUCCESS) {
                std::cerr << "应该拒绝空解码器名称" << std::endl;
                return false;
            }
            
            // 测试不存在的解码器
            VideoDecoderParams nonExistentParams;
            nonExistentParams.codecName = "non_existent_codec";
            
            result = decoder->open(nonExistentParams);
            if (result == ErrorCode::SUCCESS) {
                std::cerr << "应该拒绝不存在的解码器" << std::endl;
                return false;
            }
            
            // 测试状态错误
            auto decoder2 = std::make_unique<VideoDecoder>();
            VideoDecoderParams emptyParams;
            result = decoder2->open(emptyParams); // 空参数打开
            if (result == ErrorCode::SUCCESS) {
                std::cerr << "应该拒绝空参数的打开操作" << std::endl;
                return false;
            }
            
            std::cout << "错误处理测试通过" << std::endl;
            return true;
            
        } catch (const std::exception& e) {
            std::cerr << "错误处理测试异常: " << e.what() << std::endl;
            return false;
        }
    }
    
    // 运行所有测试
    bool runAllTests() {
        std::cout << "\n开始运行解码器测试套件..." << std::endl;
        
        bool allPassed = true;
        
        allPassed &= testVideoDecoderBasic();
        allPassed &= testAudioDecoderBasic();
        allPassed &= testHardwareDecoder();
        allPassed &= testDecoderFactory();
        allPassed &= testDecoderStateManagement();
        allPassed &= testErrorHandling();
        
        std::cout << "\n=== 测试结果 ===" << std::endl;
        if (allPassed) {
            std::cout << "✅ 所有测试通过！" << std::endl;
        } else {
            std::cout << "❌ 部分测试失败！" << std::endl;
        }
        
        return allPassed;
    }
};

int main() {
    try {
        DecoderTester tester;
        bool success = tester.runAllTests();
        return success ? 0 : 1;
    } catch (const std::exception& e) {
        std::cerr << "程序异常: " << e.what() << std::endl;
        return 1;
    } catch (...) {
        std::cerr << "未知异常" << std::endl;
        return 1;
    }
}
