#ifndef __ZVFS_SPDK_ENGINE_H__
#define __ZVFS_SPDK_ENGINE_H__

#include "common/uthash.h"
#include "proto/ipc_proto.h"
#include <stdint.h>
#include <sys/types.h>
#include <stdatomic.h>
#include <spdk/blob.h>


// blob_handle 结构体：底层 blob 信息，不含文件级 size（上层维护）
typedef struct zvfs_blob_handle {
    spdk_blob_id         blob_id;
    struct spdk_blob    *blob;         
    void                *dma_buf;      
    uint64_t             dma_buf_size; 
    atomic_uint          ref_count;
} zvfs_blob_handle_t;

struct zvfs_io_thread {
    struct spdk_thread     *thread;
    struct spdk_io_channel *channel;   // 每个 io 线程独占一个 channel
    pthread_t               tid;
    bool                    ready;
};

typedef uint64_t    zvfs_handle_id_t;

struct zvfs_blob_cache_entry {
    zvfs_handle_id_t              handle_id;   // key != blob_id
    struct zvfs_blob_handle *handle;
    UT_hash_handle           hh;
};

typedef struct zvfs_spdk_io_engine {
    struct spdk_bs_dev      *bs_dev;
    struct spdk_blob_store  *bs;


    /* 线程池：thread_pool[0] 固定为 md 线程，其余为 io 线程 */
    struct zvfs_io_thread   *thread_pool;       // 线程池
    int                      thread_count;      // 总线程数 (= CPU 核心数)
    int                      io_thread_count;   // 线程数量

    struct zvfs_blob_cache_entry *handle_cache;   // handle_id -> handle 映射
    pthread_mutex_t               cache_mu;

    uint64_t                 io_unit_size;
    uint64_t                 cluster_size;
} zvfs_spdk_io_engine_t;


int engine_cache_insert(struct zvfs_blob_handle *handle, zvfs_handle_id_t *out_id);
struct zvfs_blob_handle *engine_cache_lookup(zvfs_handle_id_t handle_id);
void engine_cache_remove(zvfs_handle_id_t handle_id);

int io_engine_init(const char *bdev_name, const char *json_file, int thread_num);
int blob_create(struct zvfs_req *req);
int blob_open(struct zvfs_req *req);
int blob_write(struct zvfs_req *req);
int blob_read(struct zvfs_req *req);
int blob_resize(struct zvfs_req *req);
int blob_sync_md(struct zvfs_req *req);
int blob_close(struct zvfs_req *req);
int blob_delete(struct zvfs_req *req);
int blobstore_reset(struct zvfs_req *req);
bool io_engine_reset_in_progress(void);

#endif // __ZVFS_IO_ENGINE_H__
