#include <chrono>
#include <iostream>
#include <string>
#include <thread>

#include "code/base/logger.h"
#include "code/player/player_core_v2.h"

using namespace av::player;
using namespace av::utils;

// 简单的事件回调类
class TestPlayerCallback : public PlayerEventCallback {
public:
    void onStateChanged(PlayerState newState) override {
        std::string stateStr;
        switch (newState) {
            case PlayerState::Idle: stateStr = "Idle"; break;
            case PlayerState::Opening: stateStr = "Opening"; break;
            case PlayerState::Stopped: stateStr = "Stopped"; break;
            case PlayerState::Playing: stateStr = "Playing"; break;
            case PlayerState::Paused: stateStr = "Paused"; break;
            case PlayerState::Seeking: stateStr = "Seeking"; break;
            case PlayerState::Error: stateStr = "Error"; break;
        }
        std::cout << "[EVENT] State changed to: " << stateStr << std::endl;
    }
    
    void onPositionChanged(int64_t position) override {
        static auto lastUpdate = std::chrono::steady_clock::now();
        auto now = std::chrono::steady_clock::now();
        if (std::chrono::duration_cast<std::chrono::seconds>(now - lastUpdate).count() >= 1) {
            double seconds = position / 1000000.0;
            std::cout << "[EVENT] Position: " << std::fixed << std::setprecision(2) << seconds << "s" << std::endl;
            lastUpdate = now;
        }
    }
    
    void onMediaInfoChanged(const MediaInfo& info) override {
        std::cout << "[EVENT] Media info changed:" << std::endl;
        std::cout << "  File: " << info.filename << std::endl;
        std::cout << "  Duration: " << (info.duration / 1000000.0) << "s" << std::endl;
        std::cout << "  Has Video: " << (info.hasVideo ? "Yes" : "No") << std::endl;
        std::cout << "  Has Audio: " << (info.hasAudio ? "Yes" : "No") << std::endl;
        
        if (info.hasAudio) {
            std::cout << "  Audio: " << info.sampleRate << " Hz, " << info.channels << " channels" << std::endl;
        }
    }
    
    void onErrorOccurred(const std::string& error) override {
        std::cout << "[ERROR] " << error << std::endl;
    }
    
    void onFrameDropped(int64_t totalDropped) override {
        std::cout << "[WARNING] Frame dropped, total: " << totalDropped << std::endl;
    }
    
    void onSyncError(double error, const std::string& reason) override {
        std::cout << "[WARNING] Sync error: " << (error * 1000) << "ms, reason: " << reason << std::endl;
    }

    void onEndOfFile() override {}
};

int main() {
    // 初始化日志系统
    Logger::instance().setLevel(LogLevel::DEBUG);
    Logger::instance().info("Audio Test Started");
    
    try {
        // 创建同步配置
        SyncConfigV2 syncConfig;
        syncConfig.syncStrategy = SyncStrategy::ADAPTIVE;
        syncConfig.audioSyncThreshold = 0.040;
        syncConfig.videoSyncThreshold = 0.020;
        syncConfig.maxSyncError = 0.200;
        syncConfig.clockUpdateInterval = 10;
        syncConfig.smoothingWindow = 10;
        syncConfig.enableAdaptiveSync = true;
        syncConfig.enableFrameDrop = true;
        syncConfig.enableFrameDuplicate = true;
        syncConfig.enablePrediction = true;
        syncConfig.enableErrorRecovery = true;
        
        // 创建播放器实例
        auto player = std::make_unique<PlayerCoreV2>(syncConfig);
        
        // 创建事件回调
        auto callback = std::make_unique<TestPlayerCallback>();
        player->setEventCallback(callback.get());
        
        // 测试音频文件路径（请根据实际情况修改）
        std::string audioFile = "C:\\Windows\\Media\\notify.wav"; // Windows系统音频文件
        
        std::cout << "Testing with audio file: " << audioFile << std::endl;
        
        // 打开音频文件
        auto result = player->openFile(audioFile);
        if (result != ErrorCode::SUCCESS) {
            std::cout << "Failed to open audio file: " << static_cast<int>(result) << std::endl;
            
            // 尝试其他常见的音频文件
            audioFile = "C:\\Windows\\Media\\chimes.wav";
            std::cout << "Trying alternative file: " << audioFile << std::endl;
            result = player->openFile(audioFile);
            
            if (result != ErrorCode::SUCCESS) {
                std::cout << "Failed to open alternative audio file: " << static_cast<int>(result) << std::endl;
                std::cout << "Please provide a valid audio file path." << std::endl;
                return 1;
            }
        }
        
        std::cout << "Audio file opened successfully!" << std::endl;
        
        // 获取媒体信息
        auto mediaInfo = player->getMediaInfo();
        std::cout << "Media duration: " << (mediaInfo.duration / 1000000.0) << " seconds" << std::endl;
        std::cout << "Has audio: " << (mediaInfo.hasAudio ? "Yes" : "No") << std::endl;
        
        if (!mediaInfo.hasAudio) {
            std::cout << "No audio stream found in the file!" << std::endl;
            return 1;
        }
        
        // 设置音量为最大
        player->setVolume(1.0);
        std::cout << "Volume set to: " << player->getVolume() << std::endl;
        
        // 开始播放
        result = player->play();
        if (result != ErrorCode::SUCCESS) {
            std::cout << "Failed to start playback: " << static_cast<int>(result) << std::endl;
            return 1;
        }
        
        std::cout << "Playback started! You should hear audio now." << std::endl;
        std::cout << "Current volume: " << player->getVolume() << std::endl;
        
        // 等待播放完成
        double totalDuration = mediaInfo.duration / 1000000.0;
        std::cout << "Waiting for playback to complete (" << totalDuration << " seconds)..." << std::endl;
        
        // 监控播放状态
        auto startTime = std::chrono::steady_clock::now();
        while (true) {
            auto currentTime = std::chrono::steady_clock::now();
            auto elapsed = std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count();
            
            auto state = player->getState();
            auto currentPos = player->getCurrentTime() / 1000000.0;
            
            std::cout << "State: " << static_cast<int>(state) << ", Position: " << currentPos << "s" << std::endl;
            
            // 如果播放完成或出错，退出
            if (state == PlayerState::Stopped || state == PlayerState::Error) {
                break;
            }
            
            // 如果播放时间接近总时长，停止播放
            if (currentPos >= totalDuration - 0.1) {
                std::cout << "Playback completed, stopping..." << std::endl;
                player->stop();
                break;
            }
            
            // 超时保护
            if (elapsed > totalDuration + 5) {
                std::cout << "Timeout, stopping playback..." << std::endl;
                player->stop();
                break;
            }
            
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }
        
        std::cout << "Audio test completed." << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "Exception: " << e.what() << std::endl;
        return 1;
    } catch (...) {
        std::cerr << "Unknown exception occurred" << std::endl;
        return 1;
    }
    
    return 0;
}
