#include "recorder.h"
#include "../base/logger.h"
#include <filesystem>
#include <algorithm>

namespace av {
namespace recorder {

// 静态成员初始化
bool RecorderModule::initialized_ = false;

ErrorCode RecorderModule::initialize() {
    if (initialized_) {
        return ErrorCode::SUCCESS;
    }
    
    AV_LOGGER_INFOF("Initializing Recorder Module v{}", getVersion());
    
    // TODO: 初始化FFmpeg库（如果需要）
    // TODO: 检查硬件编码器支持
    // TODO: 初始化音频设备枚举
    
    initialized_ = true;
    
    AV_LOGGER_INFO("Recorder Module initialized successfully");
    return ErrorCode::SUCCESS;
}

void RecorderModule::cleanup() {
    if (!initialized_) {
        return;
    }
    
    AV_LOGGER_INFO("Cleaning up Recorder Module");
    
    // TODO: 清理资源
    
    initialized_ = false;
    
    AV_LOGGER_INFO("Recorder Module cleaned up");
}

bool RecorderModule::isInitialized() {
    return initialized_;
}

std::vector<std::string> RecorderModule::getSupportedFormats() {
    return {
        "mp4", "avi", "mkv", "mov", "flv", "webm",
        "mp3", "wav", "aac", "ogg", "flac"
    };
}

std::vector<std::string> RecorderModule::getSupportedAudioCodecs() {
    return {
        "aac", "mp3", "opus", "vorbis", "flac", "pcm_s16le"
    };
}

std::vector<std::string> RecorderModule::getSupportedVideoCodecs() {
    return {
        "h264", "h265", "vp8", "vp9", "av1", "mpeg4"
    };
}

namespace utils {

AudioRecorderParams getDefaultAudioParams() {
    AudioRecorderParams params;
    params.capturerType = capture::CapturerType::AUDIO_MIC;
    params.sampleRate = 44100;
    params.channels = 2;
    params.bitsPerSample = 16;
    params.sampleFormat = AV_SAMPLE_FMT_S16;
    params.codecName = "aac";
    params.bitrate = 128000;
    params.volumeScale = 1.0f;
    params.enableMixing = false;
    params.format = "mp4";
    return params;
}

VideoRecorderParams getDefaultVideoParams() {
    VideoRecorderParams params;
    params.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
    params.monitorIndex = 0;
    params.width = 1920;
    params.height = 1080;
    params.frameRate = 30;
    params.pixelFormat = AV_PIX_FMT_YUV420P;
    params.codecName = "h264";
    params.bitrate = 5000000; // 5 Mbps
    params.keyFrameInterval = 30;
    params.preset = "medium";
    params.drawCursor = true;
    params.captureAudio = false;
    params.format = "mp4";
    return params;
}

AVRecorderParams getDefaultAVParams() {
    AVRecorderParams params;
    params.audioParams = getDefaultAudioParams();
    params.videoParams = getDefaultVideoParams();
    params.enableAudio = true;
    params.enableVideo = true;
    params.enableSync = true;
    params.syncThresholdMs = 40;
    params.dropFrameOnSync = true;
    params.format = "mp4";
    return params;
}

bool isValidOutputPath(const std::string& path) {
    if (path.empty()) {
        return false;
    }
    
    try {
        std::filesystem::path fsPath(path);
        
        // 检查父目录是否存在或可创建
        auto parentPath = fsPath.parent_path();
        if (!parentPath.empty() && !std::filesystem::exists(parentPath)) {
            // 尝试创建目录
            std::error_code ec;
            std::filesystem::create_directories(parentPath, ec);
            if (ec) {
                AV_LOGGER_ERRORF("Cannot create output directory: {}", ec.message());
                return false;
            }
        }
        
        // 检查文件扩展名
        auto extension = fsPath.extension().string();
        if (extension.empty()) {
            return false;
        }
        
        // 转换为小写
        std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
        
        // 检查是否为支持的格式
        auto supportedFormats = RecorderModule::getSupportedFormats();
        auto formatName = extension.substr(1); // 去掉点号
        
        return std::find(supportedFormats.begin(), supportedFormats.end(), formatName) != supportedFormats.end();
        
    } catch (const std::exception& e) {
        AV_LOGGER_ERRORF("Invalid output path: {}", e.what());
        return false;
    }
}

VideoRecorderParams getRecommendedVideoParams() {
    VideoRecorderParams params = getDefaultVideoParams();
    
    // TODO: 根据系统性能调整参数
    // 这里可以检查：
    // - CPU性能
    // - 可用内存
    // - 硬件编码器支持
    // - 显示器分辨率
    
    // 简单的性能检测示例
    auto availableMemory = std::thread::hardware_concurrency(); // 简化的性能指标
    
    if (availableMemory <= 4) {
        // 低性能设置
        params.width = 1280;
        params.height = 720;
        params.frameRate = 24;
        params.bitrate = 2000000; // 2 Mbps
        params.preset = "fast";
    } else if (availableMemory <= 8) {
        // 中等性能设置
        params.width = 1920;
        params.height = 1080;
        params.frameRate = 30;
        params.bitrate = 5000000; // 5 Mbps
        params.preset = "medium";
    } else {
        // 高性能设置
        params.width = 1920;
        params.height = 1080;
        params.frameRate = 60;
        params.bitrate = 8000000; // 8 Mbps
        params.preset = "slow";
    }
    
    AV_LOGGER_INFOF("Recommended video params: {}x{} @ {}fps, {} bps", 
             params.width, params.height, params.frameRate, params.bitrate);
    
    return params;
}

} // namespace utils

} // namespace recorder
} // namespace av