#include "recorder_av_recorder.h"
#include "../base/logger.h"
#include <algorithm>
#include <chrono>

namespace av {
namespace recorder {

AVRecorder::AVRecorder()
    : AbstractRecorder(MediaType::UNKNOWN)
    , shouldStopSync_(false)
    , audioTimestamp_(0)
    , videoTimestamp_(0)
    , audioEnabled_(true)
    , videoEnabled_(true)
    , syncEnabled_(true)
    , syncThreshold_(40)
    , dropFrameOnSync_(true)
    , audioPacketCount_(0)
    , videoPacketCount_(0) {
    
    recordingStartTime_ = std::chrono::steady_clock::now();
}

AVRecorder::~AVRecorder() {
    close();
}

ErrorCode AVRecorder::initialize(const RecorderParams& params) {
    if (!validateParams(params)) {
        return ErrorCode::INVALID_PARAMS;
    }
    
    avParams_ = static_cast<const AVRecorderParams&>(params);
    params_ = params;
    
    audioEnabled_ = avParams_.enableAudio;
    videoEnabled_ = avParams_.enableVideo;
    syncEnabled_ = avParams_.enableSync;
    syncThreshold_ = avParams_.syncThresholdMs;
    dropFrameOnSync_ = avParams_.dropFrameOnSync;
    
    // 初始化子录制器
    ErrorCode result = initializeSubRecorders();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    // 初始化同步器
    if (syncEnabled_ && audioEnabled_ && videoEnabled_) {
        result = initializeSynchronizer();
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_WARNING("Failed to initialize synchronizer, continuing without sync");
            syncEnabled_ = false;
        }
    }
    
    setState(RecorderState::INITIALIZED);
    return ErrorCode::SUCCESS;
}

ErrorCode AVRecorder::startRecording() {
    if (getState() != RecorderState::INITIALIZED && getState() != RecorderState::STOPPED) {
        return ErrorCode::INVALID_STATE;
    }
    
    shouldStopSync_ = false;
    recordingStartTime_ = std::chrono::steady_clock::now();
    
    // 重置统计信息
    {
        std::lock_guard<std::mutex> lock(statsMutex_);
        combinedStats_ = CombinedStats{};
    }
    
    {
        std::lock_guard<std::mutex> lock(syncMutex_);
        syncStatus_ = SyncStatus{};
    }
    
    audioTimestamp_ = 0;
    videoTimestamp_ = 0;
    audioPacketCount_ = 0;
    videoPacketCount_ = 0;
    
    // 启动音频录制器
    if (audioEnabled_ && audioRecorder_) {
        ErrorCode result = audioRecorder_->startRecording();
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to start audio recording: {}", static_cast<int>(result));
            return result;
        }
    }
    
    // 启动视频录制器
    if (videoEnabled_ && videoRecorder_) {
        ErrorCode result = videoRecorder_->startRecording();
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to start video recording: {}", static_cast<int>(result));
            // 如果视频启动失败，停止音频
            if (audioEnabled_ && audioRecorder_) {
                audioRecorder_->stopRecording();
            }
            return result;
        }
    }
    
    // 启动同步线程
    if (syncEnabled_ && audioEnabled_ && videoEnabled_) {
        syncThread_ = std::make_unique<std::thread>(&AVRecorder::synchronizationThread, this);
    }
    
    setState(RecorderState::RECORDING);
    resetStats();
    
    AV_LOGGER_INFOF("AV recording started - Audio: {}, Video: {}, Sync: {}", 
             audioEnabled_.load(), videoEnabled_.load(), syncEnabled_.load());
    return ErrorCode::SUCCESS;
}

ErrorCode AVRecorder::stopRecording() {
    if (getState() != RecorderState::RECORDING && getState() != RecorderState::PAUSED) {
        return ErrorCode::INVALID_STATE;
    }
    
    shouldStopSync_ = true;
    
    // 等待同步线程结束
    if (syncThread_ && syncThread_->joinable()) {
        syncThread_->join();
        syncThread_.reset();
    }
    
    // 停止子录制器
    ErrorCode audioResult = ErrorCode::SUCCESS;
    ErrorCode videoResult = ErrorCode::SUCCESS;
    
    if (audioEnabled_ && audioRecorder_) {
        audioResult = audioRecorder_->stopRecording();
    }
    
    if (videoEnabled_ && videoRecorder_) {
        videoResult = videoRecorder_->stopRecording();
    }
    
    setState(RecorderState::STOPPED);
    
    // 更新最终统计信息
    updateCombinedStats();
    
    AV_LOGGER_INFO("AV recording stopped");
    
    // 返回第一个错误（如果有）
    if (audioResult != ErrorCode::SUCCESS) {
        return audioResult;
    }
    return videoResult;
}

ErrorCode AVRecorder::pauseRecording() {
    if (getState() != RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    ErrorCode audioResult = ErrorCode::SUCCESS;
    ErrorCode videoResult = ErrorCode::SUCCESS;
    
    if (audioEnabled_ && audioRecorder_) {
        audioResult = audioRecorder_->pauseRecording();
    }
    
    if (videoEnabled_ && videoRecorder_) {
        videoResult = videoRecorder_->pauseRecording();
    }
    
    setState(RecorderState::PAUSED);
    
    AV_LOGGER_INFO("AV recording paused");
    
    if (audioResult != ErrorCode::SUCCESS) {
        return audioResult;
    }
    return videoResult;
}

ErrorCode AVRecorder::resumeRecording() {
    if (getState() != RecorderState::PAUSED) {
        return ErrorCode::INVALID_STATE;
    }
    
    ErrorCode audioResult = ErrorCode::SUCCESS;
    ErrorCode videoResult = ErrorCode::SUCCESS;
    
    if (audioEnabled_ && audioRecorder_) {
        audioResult = audioRecorder_->resumeRecording();
    }
    
    if (videoEnabled_ && videoRecorder_) {
        videoResult = videoRecorder_->resumeRecording();
    }
    
    setState(RecorderState::RECORDING);
    
    AV_LOGGER_INFO("AV recording resumed");
    
    if (audioResult != ErrorCode::SUCCESS) {
        return audioResult;
    }
    return videoResult;
}

void AVRecorder::close() {
    if (getState() == RecorderState::RECORDING || getState() == RecorderState::PAUSED) {
        stopRecording();
    }
    
    cleanup();
    setState(RecorderState::IDLE);
}

ErrorCode AVRecorder::setAudioEnabled(bool enabled) {
    if (getState() == RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    audioEnabled_ = enabled;
    avParams_.enableAudio = enabled;
    
    return ErrorCode::SUCCESS;
}

ErrorCode AVRecorder::setVideoEnabled(bool enabled) {
    if (getState() == RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    videoEnabled_ = enabled;
    avParams_.enableVideo = enabled;
    
    return ErrorCode::SUCCESS;
}

AVRecorder::SyncStatus AVRecorder::getSyncStatus() const {
    std::lock_guard<std::mutex> lock(syncMutex_);
    return syncStatus_;
}

void AVRecorder::setSyncThreshold(int64_t thresholdMs) {
    syncThreshold_ = thresholdMs;
    avParams_.syncThresholdMs = thresholdMs;
}

void AVRecorder::setDropFrameOnSync(bool drop) {
    dropFrameOnSync_ = drop;
    avParams_.dropFrameOnSync = drop;
}

AVRecorder::CombinedStats AVRecorder::getCombinedStats() const {
    std::lock_guard<std::mutex> lock(statsMutex_);
    
    CombinedStats stats = combinedStats_;
    
    // 更新实时数据
    if (audioRecorder_) {
        stats.audioStats = audioRecorder_->getStats();
    }
    
    if (videoRecorder_) {
        stats.videoStats = videoRecorder_->getStats();
    }
    
    stats.syncStatus = getSyncStatus();
    
    // 计算总录制时间
    auto now = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - recordingStartTime_);
    stats.totalRecordingTime = duration.count() / 1000.0;
    
    // 计算总文件大小
    stats.totalFileSize = stats.audioStats.totalBytes + stats.videoStats.totalBytes;
    
    return stats;
}

AVFramePtr AVRecorder::getCurrentVideoFrame() const {
    if (videoRecorder_) {
        return videoRecorder_->getCurrentFrame();
    }
    return nullptr;
}

float AVRecorder::getCurrentAudioLevel() const {
    if (audioRecorder_) {
        return audioRecorder_->getAudioLevel();
    }
    return 0.0f;
}

// 独立音频采集控制
ErrorCode AVRecorder::startAudioCapture() {
    if (!audioRecorder_) {
        AV_LOGGER_ERROR("Audio recorder not initialized");
        return ErrorCode::INVALID_STATE;
    }
    
    if (audioRecorder_->getState() == RecorderState::RECORDING) {
        AV_LOGGER_WARNING("Audio capture already started");
        return ErrorCode::SUCCESS;
    }
    
    ErrorCode result = audioRecorder_->startRecording();
    if (result == ErrorCode::SUCCESS) {
        audioEnabled_ = true;
        AV_LOGGER_INFO("Audio capture started independently");
    }
    
    return result;
}

ErrorCode AVRecorder::stopAudioCapture() {
    if (!audioRecorder_) {
        return ErrorCode::SUCCESS;
    }
    
    if (audioRecorder_->getState() != RecorderState::RECORDING && 
        audioRecorder_->getState() != RecorderState::PAUSED) {
        return ErrorCode::SUCCESS;
    }
    
    ErrorCode result = audioRecorder_->stopRecording();
    if (result == ErrorCode::SUCCESS) {
        AV_LOGGER_INFO("Audio capture stopped independently");
    }
    
    return result;
}

ErrorCode AVRecorder::pauseAudioCapture() {
    if (!audioRecorder_) {
        return ErrorCode::INVALID_STATE;
    }
    
    ErrorCode result = audioRecorder_->pauseRecording();
    if (result == ErrorCode::SUCCESS) {
        AV_LOGGER_INFO("Audio capture paused independently");
    }
    
    return result;
}

ErrorCode AVRecorder::resumeAudioCapture() {
    if (!audioRecorder_) {
        return ErrorCode::INVALID_STATE;
    }
    
    ErrorCode result = audioRecorder_->resumeRecording();
    if (result == ErrorCode::SUCCESS) {
        AV_LOGGER_INFO("Audio capture resumed independently");
    }
    
    return result;
}

// 独立视频采集控制
ErrorCode AVRecorder::startVideoCapture() {
    if (!videoRecorder_) {
        AV_LOGGER_ERROR("Video recorder not initialized");
        return ErrorCode::INVALID_STATE;
    }
    
    if (videoRecorder_->getState() == RecorderState::RECORDING) {
        AV_LOGGER_WARNING("Video capture already started");
        return ErrorCode::SUCCESS;
    }
    
    ErrorCode result = videoRecorder_->startRecording();
    if (result == ErrorCode::SUCCESS) {
        videoEnabled_ = true;
        AV_LOGGER_INFO("Video capture started independently");
    }
    
    return result;
}

ErrorCode AVRecorder::stopVideoCapture() {
    if (!videoRecorder_) {
        return ErrorCode::SUCCESS;
    }
    
    if (videoRecorder_->getState() != RecorderState::RECORDING && 
        videoRecorder_->getState() != RecorderState::PAUSED) {
        return ErrorCode::SUCCESS;
    }
    
    ErrorCode result = videoRecorder_->stopRecording();
    if (result == ErrorCode::SUCCESS) {
        AV_LOGGER_INFO("Video capture stopped independently");
    }
    
    return result;
}

ErrorCode AVRecorder::pauseVideoCapture() {
    if (!videoRecorder_) {
        return ErrorCode::INVALID_STATE;
    }
    
    ErrorCode result = videoRecorder_->pauseRecording();
    if (result == ErrorCode::SUCCESS) {
        AV_LOGGER_INFO("Video capture paused independently");
    }
    
    return result;
}

ErrorCode AVRecorder::resumeVideoCapture() {
    if (!videoRecorder_) {
        return ErrorCode::INVALID_STATE;
    }
    
    ErrorCode result = videoRecorder_->resumeRecording();
    if (result == ErrorCode::SUCCESS) {
        AV_LOGGER_INFO("Video capture resumed independently");
    }
    
    return result;
}

// 实时切换功能
ErrorCode AVRecorder::toggleAudioRecording(bool enable) {
    if (!audioRecorder_) {
        return ErrorCode::INVALID_STATE;
    }
    
    if (enable) {
        if (!isAudioRecording()) {
            return startAudioCapture();
        }
    } else {
        if (isAudioRecording()) {
            return pauseAudioCapture(); // 使用暂停而不是停止，保持状态
        }
    }
    
    return ErrorCode::SUCCESS;
}

ErrorCode AVRecorder::toggleVideoRecording(bool enable) {
    if (!videoRecorder_) {
        return ErrorCode::INVALID_STATE;
    }
    
    if (enable) {
        if (!isVideoRecording()) {
            return startVideoCapture();
        }
    } else {
        if (isVideoRecording()) {
            return pauseVideoCapture(); // 使用暂停而不是停止，保持状态
        }
    }
    
    return ErrorCode::SUCCESS;
}

// 状态查询
bool AVRecorder::isAudioRecording() const {
    return audioRecorder_ && 
           audioRecorder_->getState() == RecorderState::RECORDING;
}

bool AVRecorder::isVideoRecording() const {
    return videoRecorder_ && 
           videoRecorder_->getState() == RecorderState::RECORDING;
}

bool AVRecorder::isAudioCapturing() const {
    return audioRecorder_ && 
           (audioRecorder_->getState() == RecorderState::RECORDING || 
            audioRecorder_->getState() == RecorderState::PAUSED);
}

bool AVRecorder::isVideoCapturing() const {
    return videoRecorder_ && 
           (videoRecorder_->getState() == RecorderState::RECORDING || 
            videoRecorder_->getState() == RecorderState::PAUSED);
}

bool AVRecorder::validateParams(const RecorderParams& params) {
    const auto& avParams = static_cast<const AVRecorderParams&>(params);
    
    if (!avParams.enableAudio && !avParams.enableVideo) {
        AV_LOGGER_ERROR("Both audio and video are disabled");
        return false;
    }
    
    if (avParams.outputPath.empty()) {
        AV_LOGGER_ERROR("Output path is empty");
        return false;
    }
    
    // 验证音频参数
    if (avParams.enableAudio) {
        if (avParams.audioParams.sampleRate == 0 || avParams.audioParams.channels == 0) {
            AV_LOGGER_ERROR("Invalid audio parameters");
            return false;
        }
    }
    
    // 验证视频参数
    if (avParams.enableVideo) {
        if (avParams.videoParams.width == 0 || avParams.videoParams.height == 0) {
            AV_LOGGER_ERROR("Invalid video parameters");
            return false;
        }
    }
    
    return true;
}

void AVRecorder::synchronizationThread() {
    AV_LOGGER_INFO("Synchronization thread started");
    
    const auto syncInterval = std::chrono::milliseconds(100); // 100ms检查间隔
    
    try {
        while (!shouldStopSync_) {
            std::this_thread::sleep_for(syncInterval);
            
            if (getState() != RecorderState::RECORDING) {
                continue;
            }
            
            try {
                checkSyncStatus();
                updateCombinedStats();
            } catch (const std::exception& e) {
                AV_LOGGER_ERRORF("Error in sync check: {}", e.what());
                // 同步错误不应该终止整个录制过程，继续运行
            }
        }
    } catch (const std::exception& e) {
        AV_LOGGER_ERRORF("Synchronization thread crashed with exception: {}", e.what());
    } catch (...) {
        AV_LOGGER_ERROR("Synchronization thread crashed with unknown exception");
    }
    
    AV_LOGGER_INFO("Synchronization thread stopped");
}

void AVRecorder::onAudioPacket(const AVPacketPtr& packet) {
    if (packet) {
        audioTimestamp_ = packet->pts;
        audioPacketCount_++;
    }
}

void AVRecorder::onVideoPacket(const AVPacketPtr& packet) {
    if (packet) {
        videoTimestamp_ = packet->pts;
        videoPacketCount_++;
    }
}

void AVRecorder::checkSyncStatus() {
    if (!syncEnabled_ || !audioEnabled_ || !videoEnabled_) {
        return;
    }
    
    int64_t audioTs = audioTimestamp_.load();
    int64_t videoTs = videoTimestamp_.load();
    int64_t timeDiff = audioTs - videoTs;
    
    {
        std::lock_guard<std::mutex> lock(syncMutex_);
        syncStatus_.audioTimestamp = audioTs;
        syncStatus_.videoTimestamp = videoTs;
        syncStatus_.timeDiff = timeDiff;
        syncStatus_.isInSync = std::abs(timeDiff) <= syncThreshold_;
    }
    
    // 如果不同步，尝试调整
    if (!syncStatus_.isInSync && dropFrameOnSync_) {
        adjustSync(timeDiff);
    }
}

void AVRecorder::adjustSync(int64_t timeDiff) {
    // 简单的同步策略：丢弃超前的帧
    if (timeDiff > syncThreshold_) {
        // 音频超前，通知音频录制器丢帧
        std::lock_guard<std::mutex> lock(syncMutex_);
        syncStatus_.droppedAudioFrames++;
    } else if (timeDiff < -syncThreshold_) {
        // 视频超前，通知视频录制器丢帧
        std::lock_guard<std::mutex> lock(syncMutex_);
        syncStatus_.droppedVideoFrames++;
    }
}

ErrorCode AVRecorder::initializeSubRecorders() {
    // 初始化音频录制器
    if (avParams_.enableAudio) {
        audioRecorder_ = std::make_unique<AudioRecorder>();
        
        // 设置输出路径（音频部分）
        auto audioParams = avParams_.audioParams;
        audioParams.outputPath = avParams_.outputPath;
        
        ErrorCode result = audioRecorder_->initialize(audioParams);
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to initialize audio recorder: {}", static_cast<int>(result));
            return result;
        }
    }
    
    // 初始化视频录制器
    if (avParams_.enableVideo) {
        videoRecorder_ = std::make_unique<VideoRecorder>();
        
        // 设置输出路径（视频部分）
        auto videoParams = avParams_.videoParams;
        videoParams.outputPath = avParams_.outputPath;
        
        ErrorCode result = videoRecorder_->initialize(videoParams);
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to initialize video recorder: {}", static_cast<int>(result));
            return result;
        }
    }
    
    return ErrorCode::SUCCESS;
}

ErrorCode AVRecorder::initializeSynchronizer() {
    synchronizer_ = std::make_unique<utils::SynchronizerV2>();
    
    // TODO: 配置同步器参数
    
    return ErrorCode::SUCCESS;
}

void AVRecorder::cleanup() {
    shouldStopSync_ = true;
    
    // 停止同步线程
    if (syncThread_ && syncThread_->joinable()) {
        syncThread_->join();
        syncThread_.reset();
    }
    
    // 清理子录制器
    if (audioRecorder_) {
        audioRecorder_->close();
        audioRecorder_.reset();
    }
    
    if (videoRecorder_) {
        videoRecorder_->close();
        videoRecorder_.reset();
    }
    
    // 清理同步器
    if (synchronizer_) {
        synchronizer_.reset();
    }
}

void AVRecorder::updateCombinedStats() {
    std::lock_guard<std::mutex> lock(statsMutex_);
    
    if (audioRecorder_) {
        combinedStats_.audioStats = audioRecorder_->getStats();
    }
    
    if (videoRecorder_) {
        combinedStats_.videoStats = videoRecorder_->getStats();
    }
    
    combinedStats_.syncStatus = getSyncStatus();
}

// RecorderFactoryImpl 实现
std::unique_ptr<AudioRecorder> RecorderFactoryImpl::createAudioRecorder() {
    return std::make_unique<AudioRecorder>();
}

std::unique_ptr<VideoRecorder> RecorderFactoryImpl::createVideoRecorder() {
    return std::make_unique<VideoRecorder>();
}

std::unique_ptr<AVRecorder> RecorderFactoryImpl::createAVRecorder() {
    return std::make_unique<AVRecorder>();
}

std::unique_ptr<AbstractRecorder> RecorderFactoryImpl::createRecorder(MediaType mediaType) {
    switch (mediaType) {
        case MediaType::AUDIO:
            return createAudioRecorder();
        case MediaType::VIDEO:
            return createVideoRecorder();
        case MediaType::UNKNOWN: // 用于表示音视频混合
            return createAVRecorder();
        default:
            return nullptr;
    }
}

} // namespace recorder
} // namespace av