#ifndef __FLASH_PORT_H
#define __FLASH_PORT_H

#include <stdint.h>

#include "app_calibration.h"

#ifndef FLASH_PORT_LOG_TAG
#define FLASH_PORT_LOG_TAG "FLASH_PORT"
#endif

/*
 * Flash Region Configuration
 * Adjust Sector Size and Base Addresses for your specific MCU.
 */
#ifndef PORT_SECTOR_SIZE                          
#define PORT_SECTOR_SIZE                        (2048U) // Target MCU Sector Size
#endif

#ifndef FLASH_PORT_CREEP_REGION
#define FLASH_PORT_CREEP_REGION_ADDR            (0x08000000 + 1024 * 58)
#define FLASH_PORT_CREEP_REGION_SIZE            PORT_SECTOR_SIZE
#endif

#ifndef FLASH_PORT_DEVICE_INFO_REGION
#define FLASH_PORT_DEVICE_INFO_REGION_ADDR      (0x08000000 + 1024 * 60)
#define FLASH_PORT_DEVICE_INFO_REGION_SIZE      PORT_SECTOR_SIZE
#endif

#ifndef FLASH_PORT_CALI_REGION
#define FLASH_PORT_CALI_REGION_ADDR             (0x08000000 + 1024 * 62) // FMC_WRITE_MAP_ADDR in old code
#define FLASH_PORT_CALI_REGION_SIZE             PORT_SECTOR_SIZE
#endif

#ifndef FLASH_PORT_MAP_REGION
#define FLASH_PORT_MAP_REGION_ADDR              (FLASH_PORT_CALI_REGION_ADDR + PORT_SECTOR_SIZE) 
#define FLASH_PORT_MAP_REGION_SIZE              APP_MAP_MATRIX_BYTES
#define FLASH_PORT_MAP_WORDS                    APP_MAP_MATRIX_WORDS
#endif



/* ============================================================================
 * HAL Interface (Function pointer injection)
 * ============================================================================ */
typedef struct flash_port_ops_t
{
    uint8_t (*read)(uint32_t addr, void *buf, uint32_t len);
    uint8_t (*write)(uint32_t addr, const void *buf, uint32_t len);
    uint8_t (*erase)(uint32_t addr, uint32_t len);
    uint8_t (*is_erased)(uint32_t addr, uint32_t len);
} flash_port_ops_t;

/**
 * @brief Initialize the flash port layer with hardware specific operations.
 * @param ops Pointer to hardware operations structure.
 */
void flash_port_init(const flash_port_ops_t *ops);

/* ============================================================================
 * Application APIs
 * ============================================================================ */
uint8_t flash_port_math_load(app_math_cali_t *params);
uint8_t flash_port_math_save(const app_math_cali_t *params);
uint8_t flash_port_math_clear(void);

uint8_t flash_port_pressure_load(app_math_cali_t *params);
uint8_t flash_port_pressure_save(const app_math_cali_t *params);
uint8_t flash_port_pressure_clear(void);

uint8_t flash_port_map_load(uint16_t *map_matrix, uint32_t map_words);
uint8_t flash_port_map_save(const uint16_t *map_matrix, uint32_t map_words);
uint8_t flash_port_map_clear(void);

uint8_t flash_port_creep_load(app_creep_params *params);
uint8_t flash_port_creep_save(const app_creep_params *params);
uint8_t flash_port_creep_clear(void);

uint8_t flash_port_device_info_load(app_dev_info *info);
uint8_t flash_port_device_info_save(const app_dev_info *info);

#endif /* __FLASH_PORT_H */
