#ifndef AV_BASE_MEDIA_COMMON_H
#define AV_BASE_MEDIA_COMMON_H

#include "types.h"
#include <string>
#include <vector>
#include <memory>
#include <functional>
#include <chrono>
#include <limits>

namespace av {

// 字符串工具
namespace string_utils {
    // 字符串分割
    std::vector<std::string> split(const std::string& str, char delimiter);
    std::vector<std::string> split(const std::string& str, const std::string& delimiter);
    
    // 字符串修剪
    std::string trim(const std::string& str);
    std::string trimLeft(const std::string& str);
    std::string trimRight(const std::string& str);
    
    // 字符串替换
    std::string replace(const std::string& str, const std::string& from, const std::string& to);
    
    // 大小写转换
    std::string toLower(const std::string& str);
    std::string toUpper(const std::string& str);
    
    // 字符串判断
    bool startsWith(const std::string& str, const std::string& prefix);
    bool endsWith(const std::string& str, const std::string& suffix);
    bool contains(const std::string& str, const std::string& substr);
    
    // 格式化
    template<typename... Args>
    std::string format(const std::string& format, Args&&... args);
}

// 文件路径工具
namespace path_utils {
    // 路径操作
    std::string join(const std::string& path1, const std::string& path2);
    std::string getDirectory(const std::string& path);
    std::string getFilename(const std::string& path);
    std::string getExtension(const std::string& path);
    std::string removeExtension(const std::string& path);
    
    // 路径规范化
    std::string normalize(const std::string& path);
    std::string toNative(const std::string& path);
    
    // 路径判断
    bool exists(const std::string& path);
    bool isFile(const std::string& path);
    bool isDirectory(const std::string& path);
    bool isAbsolute(const std::string& path);
    
    // 目录操作
    bool createDirectory(const std::string& path);
    bool removeFile(const std::string& path);
}

// 时间工具
namespace time_utils {
    // 获取当前时间戳
    int64_t getCurrentTimeMs();
    int64_t getCurrentTimeUs();
    
    // 时间格式化
    std::string formatTime(int64_t timeMs, const std::string& format = "%Y-%m-%d %H:%M:%S");
    std::string formatDuration(int64_t durationMs);
    
    // 性能计时器
    class Timer {
    public:
        Timer();
        void start();
        void stop();
        void reset();
        int64_t elapsedMs() const;
        int64_t elapsedUs() const;
        bool isRunning() const;
        
    private:
        std::chrono::high_resolution_clock::time_point m_startTime;
        std::chrono::high_resolution_clock::time_point m_endTime;
        bool m_running = false;
    };
    
    // RAII计时器
    class ScopedTimer {
    public:
        explicit ScopedTimer(const std::string& name);
        ~ScopedTimer();
        
    private:
        std::string m_name;
        Timer m_timer;
    };
}

// 内存工具
namespace memory_utils {
    // 内存对齐
    size_t alignSize(size_t size, size_t alignment);
    void* alignedAlloc(size_t size, size_t alignment);
    void alignedFree(void* ptr);
    
    // 内存池（简单实现）
    class MemoryPool {
    public:
        explicit MemoryPool(size_t blockSize, size_t blockCount = 100);
        ~MemoryPool();
        
        void* allocate();
        void deallocate(void* ptr);
        
        size_t getBlockSize() const { return m_blockSize; }
        size_t getAvailableBlocks() const;
        
    private:
        size_t m_blockSize;
        std::vector<uint8_t> m_memory;
        std::vector<void*> m_freeBlocks;
        mutable std::mutex m_mutex;
    };
}

// FFmpeg工具
namespace ffmpeg_utils {
    // 错误处理
    std::string errorToString(int errorCode);
    bool checkError(int ret, const std::string& operation);
    
    // 格式转换
    std::string pixelFormatToString(AVPixelFormat format);
    std::string sampleFormatToString(AVSampleFormat format);
    std::string codecTypeToString(AVMediaType type);
    
    // 参数验证
    bool isValidPixelFormat(AVPixelFormat format);
    bool isValidSampleFormat(AVSampleFormat format);
    bool isValidSampleRate(int sampleRate);
    bool isValidChannels(int channels);
    
    // 帧工具
    // 统一使用智能指针的帧分配函数
AVFramePtr allocateFrame(AVPixelFormat format, int width, int height);
AVFramePtr allocateAudioFrame(AVSampleFormat format, int sampleRate, int channels, int nbSamples);
    void freeFrame(AVFrame** frame);
    
    // 包工具
    AVPacket* allocatePacket();
    void freePacket(AVPacket** packet);
    
    // 初始化
    bool initializeFFmpeg();
    void cleanupFFmpeg();
}

// 数学工具
namespace math_utils {
    // 数值限制
    template<typename T>
    T clamp(T value, T min, T max) {
        return (value < min) ? min : (value > max) ? max : value;
    }
    
    // 数值转换
    template<typename T, typename U>
    T safeCast(U value) {
        return static_cast<T>(clamp<U>(value, 
            static_cast<U>(std::numeric_limits<T>::min()),
            static_cast<U>(std::numeric_limits<T>::max())));
    }
    
    // 对齐
    template<typename T>
    T alignUp(T value, T alignment) {
        return (value + alignment - 1) / alignment * alignment;
    }
    
    template<typename T>
    T alignDown(T value, T alignment) {
        return value / alignment * alignment;
    }
}

// 线程安全的单例模板
template<typename T>
class Singleton {
public:
    static T& instance() {
        static T instance;
        return instance;
    }
    
protected:
    Singleton() = default;
    virtual ~Singleton() = default;
    
private:
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};

// RAII资源管理器
template<typename Resource, typename Deleter>
class ResourceGuard {
public:
    explicit ResourceGuard(Resource resource, Deleter deleter)
        : m_resource(resource), m_deleter(deleter), m_valid(true) {}
    
    ~ResourceGuard() {
        if (m_valid && m_resource) {
            m_deleter(m_resource);
        }
    }
    
    // 移动构造
    ResourceGuard(ResourceGuard&& other) noexcept
        : m_resource(other.m_resource), m_deleter(std::move(other.m_deleter)), m_valid(other.m_valid) {
        other.m_valid = false;
    }
    
    // 移动赋值
    ResourceGuard& operator=(ResourceGuard&& other) noexcept {
        if (this != &other) {
            if (m_valid && m_resource) {
                m_deleter(m_resource);
            }
            m_resource = other.m_resource;
            m_deleter = std::move(other.m_deleter);
            m_valid = other.m_valid;
            other.m_valid = false;
        }
        return *this;
    }
    
    // 禁止拷贝
    ResourceGuard(const ResourceGuard&) = delete;
    ResourceGuard& operator=(const ResourceGuard&) = delete;
    
    Resource get() const { return m_resource; }
    Resource release() {
        m_valid = false;
        return m_resource;
    }
    
    bool isValid() const { return m_valid; }
    
private:
    Resource m_resource;
    Deleter m_deleter;
    bool m_valid;
};

// 便捷的资源管理器创建函数
template<typename Resource, typename Deleter>
ResourceGuard<Resource, Deleter> makeResourceGuard(Resource resource, Deleter deleter) {
    return ResourceGuard<Resource, Deleter>(resource, deleter);
}

} // namespace av

// 便捷宏定义
#define AV_SCOPED_TIMER(name) av::time_utils::ScopedTimer _timer(name)
#define AV_MEASURE_TIME(name, code) \
    do { \
        av::time_utils::Timer _timer; \
        _timer.start(); \
        code; \
        _timer.stop(); \
        AV_LOGGER_INFOF("{} took {} ms", name, _timer.elapsedMs()); \
    } while(0)

#endif // AV_BASE_MEDIA_COMMON_H