#include "recorder_audio_recorder.h"
#include "../base/logger.h"
#include "../capture/capture_audio_capturer.h"
#include "../codec/codec_audio_encoder.h"
#include "../muxer/muxer_file_muxer.h"
#include <algorithm>
#include <cmath>

extern "C" {
#include <libavutil/channel_layout.h>
}

namespace av {
namespace recorder {
AudioRecorder::AudioRecorder()
    : AbstractRecorder(MediaType::AUDIO)
    , shouldStop_(false)
    , volumeScale_(1.0f)
    , currentAudioLevel_(0.0f)
    , isPaused_(false)
    , processedSamples_(0)
{
    threadPool_ = std::make_unique<utils::ThreadPool>(); // 2个工作线程
    lastProcessTime_ = std::chrono::steady_clock::now();
}

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

ErrorCode AudioRecorder::initialize(const RecorderParams& params) {
    if (!validateParams(params)) {
        return ErrorCode::INVALID_PARAMS;
    }
    
    audioParams_ = static_cast<const AudioRecorderParams&>(params);
    params_ = params;
    
    // 初始化各个组件
    ErrorCode result = initializeCapturers();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    result = initializeEncoder();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    result = initializeMuxer();
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    setState(RecorderState::INITIALIZED);
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::startRecording() {
    if (getState() != RecorderState::INITIALIZED && getState() != RecorderState::STOPPED) {
        return ErrorCode::INVALID_STATE;
    }
    
    shouldStop_ = false;
    isPaused_ = false;
    
    // 启动采集器
    for (auto& capturer : capturers_) {
        ErrorCode result = capturer->start();
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to start audio capturer: {}", static_cast<int>(result));
            return result;
        }
    }
    
    // 启动音频处理线程
    processingThread_ = std::make_unique<std::thread>(&AudioRecorder::audioProcessingThread, this);
    
    setState(RecorderState::RECORDING);
    resetStats();
    
    AV_LOGGER_INFO("Audio recording started");
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::stopRecording() {
    if (getState() != RecorderState::RECORDING && getState() != RecorderState::PAUSED) {
        return ErrorCode::INVALID_STATE;
    }
    
    shouldStop_ = true;
    isPaused_ = false;
    
    // 通知处理线程停止
    queueCondition_.notify_all();
    
    // 等待处理线程结束
    if (processingThread_ && processingThread_->joinable()) {
        processingThread_->join();
        processingThread_.reset();
    }
    
    // 停止采集器
    for (auto& capturer : capturers_) {
        capturer->stop();
    }
    
    // 刷新编码器
    if (encoder_) {
        std::vector<AVPacketPtr> packets;
        encoder_->finishEncode(packets);
        
        for (const auto& packet : packets) {
            if (muxer_) {
                muxer_->writePacket(packet.get());
            }
        }
    }
    
    // 关闭复用器
    if (muxer_) {
        muxer_->close();
    }
    
    setState(RecorderState::STOPPED);
    
    AV_LOGGER_INFO("Audio recording stopped");
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::pauseRecording() {
    if (getState() != RecorderState::RECORDING) {
        return ErrorCode::INVALID_STATE;
    }
    
    isPaused_ = true;
    setState(RecorderState::PAUSED);
    
    AV_LOGGER_INFO("Audio recording paused");
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::resumeRecording() {
    if (getState() != RecorderState::PAUSED) {
        return ErrorCode::INVALID_STATE;
    }
    
    isPaused_ = false;
    setState(RecorderState::RECORDING);
    
    AV_LOGGER_INFO("Audio recording resumed");
    return ErrorCode::SUCCESS;
}

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

void AudioRecorder::setVolumeScale(float scale) {
    volumeScale_ = std::max(0.0f, std::min(2.0f, scale)); // 限制在0-2之间
}

float AudioRecorder::getAudioLevel() const {
    std::lock_guard<std::mutex> lock(audioLevelMutex_);
    return currentAudioLevel_;
}

ErrorCode AudioRecorder::addAudioDevice(const std::string& deviceId, capture::CapturerType type) {
    std::lock_guard<std::mutex> lock(capturerMutex_);
    
    // 创建新的采集器
    auto capturer = std::make_unique<capture::AudioCapturer>();
    
    capture::AudioCaptureParams capturerParams(type);
    capturerParams.deviceId = deviceId;
    
    ErrorCode result = capturer->initialize(capturerParams);
    if (result != ErrorCode::SUCCESS) {
        return result;
    }
    
    // 设置回调
    size_t capturerIndex = capturers_.size();
    capturer->setFrameCallback([this, capturerIndex](const AVFramePtr& frame) {
        onAudioFrameCaptured(frame, capturerIndex);
    });
    
    capturers_.push_back(std::move(capturer));
    
    AV_LOGGER_INFOF("Added audio device: {}", deviceId);
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::removeAudioDevice(const std::string& deviceId) {
    std::lock_guard<std::mutex> lock(capturerMutex_);
    
    auto it = std::find_if(capturers_.begin(), capturers_.end(),
        [&deviceId](const std::unique_ptr<capture::AudioCapturer>& capturer) {
            return capturer->getCurrentDevice() == deviceId;
        });
    
    if (it != capturers_.end()) {
        (*it)->stop();
        (*it)->close();
        capturers_.erase(it);
        
        AV_LOGGER_INFOF("Removed audio device: {}", deviceId);
        return ErrorCode::SUCCESS;
    }
    
    return ErrorCode::DEVICE_NOT_FOUND;
}

std::vector<std::string> AudioRecorder::getAvailableDevices(capture::CapturerType type) const {
    (void)type; // 避免未使用参数警告
    auto capturer = std::make_unique<capture::AudioCapturer>();
    return capturer->getAvailableDevices();
}

bool AudioRecorder::validateParams(const RecorderParams& params) {
    const auto& audioParams = static_cast<const AudioRecorderParams&>(params);
    
    if (audioParams.sampleRate == 0 || audioParams.channels == 0) {
        AV_LOGGER_ERRORF("Invalid audio parameters: sampleRate={}, channels={}",
                  audioParams.sampleRate, audioParams.channels);
        return false;
    }
    
    if (audioParams.outputPath.empty()) {
        AV_LOGGER_ERROR("Output path is empty");
        return false;
    }
    
    return true;
}

void AudioRecorder::audioProcessingThread() {
    AV_LOGGER_INFO("Audio processing thread started");
    
    try {
        while (!shouldStop_) {
            std::unique_lock<std::mutex> lock(queueMutex_);
            
            // 等待音频帧或停止信号
            queueCondition_.wait(lock, [this] {
                return !frameQueue_.empty() || shouldStop_;
            });
            
            if (shouldStop_) {
                break;
            }
            
            // 处理队列中的音频帧
            std::vector<AudioFrameData> framesToProcess;
            while (!frameQueue_.empty()) {
                framesToProcess.push_back(std::move(frameQueue_.front()));
                frameQueue_.pop_front();
            }
            
            lock.unlock();
            
            if (isPaused_) {
                continue;
            }
            
            // 按时间戳排序
            std::sort(framesToProcess.begin(), framesToProcess.end(),
                [](const AudioFrameData& a, const AudioFrameData& b) {
                    return a.timestamp < b.timestamp;
                });
            
            // 处理音频帧
            for (auto& frameData : framesToProcess) {
                if (shouldStop_ || isPaused_) {
                    break;
                }
                
                try {
                    // 检查帧是否有效
                    if (!frameData.frame) {
                        AV_LOGGER_WARNING("Skipping null audio frame");
                        continue;
                    }
                    
                    // 验证音频帧数据
                    if (frameData.frame->nb_samples <= 0 || !frameData.frame->data[0]) {
                        AV_LOGGER_WARNING("Invalid audio frame data, skipping");
                        continue;
                    }
                    
                    // 在移动之前保存需要的值
                    int nbSamples = frameData.frame->nb_samples;
                    
                    // 应用音量缩放
                    AVFramePtr processedFrame = std::move(frameData.frame);
                    if (volumeScale_ != 1.0f) {
                        // TODO: 实现音量缩放
                    }
                    
                    // 计算音频电平
                    {
                        std::lock_guard<std::mutex> levelLock(audioLevelMutex_);
                        // TODO: 计算RMS音频电平
                        currentAudioLevel_ = 0.5f; // 临时值
                    }
                    
                    // 编码音频帧
                    if (encoder_ && processedFrame) {
                        // 在编码前进行帧有效性检查
                        if (!processedFrame->data[0]) {
                            AV_LOGGER_ERROR("严重错误：即将编码的音频帧数据指针为空");
                            updateStats(false);
                            continue;
                        }
                        
                        AV_LOGGER_DEBUGF("准备编码音频帧: samples={}, format={}, data_ptr={}", 
                                        processedFrame->nb_samples, processedFrame->format,
                                        static_cast<void*>(processedFrame->data[0]));
                        
                        // 保存linesize用于统计（因为move后无法访问）
                        int frameLinesize = processedFrame->linesize[0];
                        
                        std::vector<AVPacketPtr> packets;
                        // 使用move语义明确转移所有权，避免潜在的双重释放
                        ErrorCode result = encoder_->encode(std::move(processedFrame), packets);
                        
                        if (result == ErrorCode::SUCCESS) {
                            for (const auto& packet : packets) {
                                if (packet && packet->size > 0) {
                                    onAudioPacketEncoded(packet);
                                }
                            }
                            updateStats(true, frameLinesize);
                        } else {
                            updateStats(false);
                            AV_LOGGER_ERRORF("Audio encoding failed: {}", static_cast<int>(result));
                        }
                    }

                    // 使用之前保存的值，而不是已经被移动的 frameData.frame
                    processedSamples_ += nbSamples;
                    
                } catch (const std::exception& e) {
                    AV_LOGGER_ERRORF("Error processing audio frame: {}", e.what());
                    updateStats(false);
                }
            }
        }
    } catch (const std::exception& e) {
        AV_LOGGER_ERRORF("Audio processing thread crashed with exception: {}", e.what());
    } catch (...) {
        AV_LOGGER_ERROR("Audio processing thread crashed with unknown exception");
    }
    
    AV_LOGGER_INFO("Audio processing thread stopped");
}

AVFramePtr AudioRecorder::mixAudioFrames(const std::vector<AVFramePtr>& frames) {
    if (frames.empty()) {
        return nullptr;
    }
    
    if (frames.size() == 1) {
        // 创建第一个帧的副本
        AVFramePtr result = av::makeAVFrame();
        if (result && frames[0] && av_frame_ref(result.get(), frames[0].get()) == 0) {
            return result;
        }
        return nullptr;
    }
    
    // TODO: 实现音频混音
    // 目前返回第一个帧的副本
    AVFramePtr result = av::makeAVFrame();
    if (result && frames[0] && av_frame_ref(result.get(), frames[0].get()) == 0) {
        return result;
    }
    return nullptr;
}

void AudioRecorder::onAudioFrameCaptured(const AVFramePtr& frame, size_t capturerIndex) {
    if (shouldStop_ || !frame) {
        return;
    }
    
    // 创建frame的副本，因为参数是const引用
    AVFramePtr frameCopy = av::makeAVFrame();
    if (!frameCopy || av_frame_ref(frameCopy.get(), frame.get()) != 0) {
        AV_LOGGER_ERROR("Failed to copy audio frame");
        return;
    }
    
    {
        std::lock_guard<std::mutex> lock(queueMutex_);
        AudioFrameData frameData;
        frameData.frame = std::move(frameCopy);
        frameData.capturerIndex = capturerIndex;
        frameData.timestamp = std::chrono::steady_clock::now();
        frameQueue_.push_back(std::move(frameData));
    }
    
    queueCondition_.notify_one();
}

void AudioRecorder::onAudioPacketEncoded(const AVPacketPtr& packet) {
    if (muxer_ && packet) {
        ErrorCode result = muxer_->writePacket(packet.get());
        if (result != ErrorCode::SUCCESS) {
            AV_LOGGER_ERRORF("Failed to write audio packet: {}", static_cast<int>(result));
        }
    }
}

ErrorCode AudioRecorder::initializeCapturers() {
    // 创建主采集器
    auto mainCapturer = std::make_unique<capture::AudioCapturer>();
    
    // 设置采集器参数，确保与录制器参数一致
    capture::AudioCaptureParams capturerParams(audioParams_.capturerType);
    capturerParams.deviceId = audioParams_.deviceId;
    capturerParams.sampleRate = audioParams_.sampleRate;
    capturerParams.channels = audioParams_.channels;
    capturerParams.sampleFormat = audioParams_.sampleFormat;
    
    AV_LOGGER_INFOF("初始化音频采集器: {}Hz, {}ch, {}", 
                   capturerParams.sampleRate, capturerParams.channels,
                   av_get_sample_fmt_name(capturerParams.sampleFormat));
    
    ErrorCode result = mainCapturer->initialize(capturerParams);
    if (result != ErrorCode::SUCCESS) {
        AV_LOGGER_ERRORF("Failed to initialize main audio capturer: {}", static_cast<int>(result));
        return result;
    }
    
    // 获取采集器实际使用的参数，更新录制器参数
    auto actualParams = mainCapturer->getCurrentParams();
    audioParams_.sampleRate = actualParams.sampleRate;
    audioParams_.channels = actualParams.channels;
    audioParams_.sampleFormat = actualParams.sampleFormat;
    
    AV_LOGGER_INFOF("采集器实际参数: {}Hz, {}ch, {}", 
                   audioParams_.sampleRate, audioParams_.channels,
                   av_get_sample_fmt_name(audioParams_.sampleFormat));
    
    // 设置回调
    mainCapturer->setFrameCallback([this](const AVFramePtr& frame) {
        onAudioFrameCaptured(frame, 0);
    });
    
    capturers_.push_back(std::move(mainCapturer));
    
    // 添加混音设备
    for (const auto& deviceId : audioParams_.mixDevices) {
        addAudioDevice(deviceId, audioParams_.capturerType);
    }
    
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::initializeEncoder() {
    encoder_ = std::make_unique<codec::AudioEncoder>();
    
    // 使用正确的AudioEncoderParams而不是基础的CodecParams
    codec::AudioEncoderParams encoderParams;
    encoderParams.type = MediaType::AUDIO;
    encoderParams.codecName = audioParams_.codecName;
    encoderParams.bitRate = audioParams_.bitrate;
    encoderParams.sampleRate = audioParams_.sampleRate;
    encoderParams.channels = audioParams_.channels;
    encoderParams.sampleFormat = audioParams_.sampleFormat;
    
    // 根据声道数设置声道布局
    if (audioParams_.channels == 1) {
        encoderParams.channelLayout = AV_CHANNEL_LAYOUT_MONO;
    } else if (audioParams_.channels == 2) {
        encoderParams.channelLayout = AV_CHANNEL_LAYOUT_STEREO;
    } else {
        av_channel_layout_default(&encoderParams.channelLayout, audioParams_.channels);
    }
    
    AV_LOGGER_INFOF("初始化音频编码器: {}Hz, {}ch, {}, {}bps", 
                   encoderParams.sampleRate, encoderParams.channels, 
                   encoderParams.codecName, encoderParams.bitRate);
    
    ErrorCode result = encoder_->open(encoderParams);
    if (result != ErrorCode::SUCCESS) {
        AV_LOGGER_ERRORF("Failed to initialize audio encoder: {}", static_cast<int>(result));
        return result;
    }
    
    return ErrorCode::SUCCESS;
}

ErrorCode AudioRecorder::initializeMuxer() {
    muxer_ = std::make_unique<muxer::FileMuxer>();
    
    // 创建音频流信息
    muxer::StreamInfo audioStreamInfo;
    audioStreamInfo.index = 0;
    audioStreamInfo.type = muxer::StreamType::AUDIO;
    audioStreamInfo.codecId = AV_CODEC_ID_AAC;  // 默认使用AAC
    audioStreamInfo.codecName = audioParams_.codecName.empty() ? "aac" : audioParams_.codecName;
    audioStreamInfo.sampleRate = audioParams_.sampleRate;
    audioStreamInfo.channels = audioParams_.channels;
    audioStreamInfo.sampleFormat = audioParams_.sampleFormat;
    audioStreamInfo.bitrate = audioParams_.bitrate;
    audioStreamInfo.timeBase = {1, static_cast<int>(audioParams_.sampleRate)};

    // 设置声道布局
    AVChannelLayout tempLayout;
    if (audioParams_.channels == 1) {
        tempLayout = AV_CHANNEL_LAYOUT_MONO;
        av_channel_layout_copy(&audioStreamInfo.channelLayout, &tempLayout);
    } else if (audioParams_.channels == 2) {
        tempLayout = AV_CHANNEL_LAYOUT_STEREO;
        av_channel_layout_copy(&audioStreamInfo.channelLayout, &tempLayout);
    } else {
        av_channel_layout_default(&audioStreamInfo.channelLayout, audioParams_.channels);
    }
    
    // 创建复用器参数并添加流信息
    muxer::FileMuxerParams muxerParams;
    muxerParams.type = muxer::MuxerType::FILE_MUXER;
    muxerParams.outputPath = audioParams_.outputPath;
    muxerParams.outputFile = audioParams_.outputPath;  // FileMuxerParams 需要设置 outputFile
    muxerParams.format = audioParams_.format;
    muxerParams.overwrite = true;  // 允许覆盖已存在文件
    muxerParams.streams.push_back(audioStreamInfo);  // 添加音频流
    
    AV_LOGGER_INFOF("添加音频流到复用器: {}Hz, {}ch, {}, {}bps", 
                   audioStreamInfo.sampleRate, audioStreamInfo.channels, 
                   audioStreamInfo.codecName, audioStreamInfo.bitrate);
    
    ErrorCode result = muxer_->initialize(muxerParams);
    if (result != ErrorCode::SUCCESS) {
        AV_LOGGER_ERRORF("Failed to initialize muxer: {}", static_cast<int>(result));
        return result;
    }
    
    return ErrorCode::SUCCESS;
}

void AudioRecorder::cleanup() {
    shouldStop_ = true;
    
    // 停止处理线程
    if (processingThread_ && processingThread_->joinable()) {
        queueCondition_.notify_all();
        processingThread_->join();
        processingThread_.reset();
    }
    
    // 清理采集器
    for (auto& capturer : capturers_) {
        if (capturer) {
            capturer->stop();
            capturer->close();
        }
    }
    capturers_.clear();
    
    // 清理编码器
    if (encoder_) {
        encoder_->close();
        encoder_.reset();
    }
    
    // 清理复用器
    if (muxer_) {
        muxer_->close();
        muxer_.reset();
    }
    
    // 清理线程池
    if (threadPool_) {
        threadPool_.reset();
    }
    
    // 清理队列
    {
        std::lock_guard<std::mutex> lock(queueMutex_);
        frameQueue_.clear();
    }
}

} // namespace recorder
} // namespace av
