#ifndef MIDEA_PROTOCOL_H
#define MIDEA_PROTOCOL_H

#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

// MideaUART Mode enumeration
typedef enum {
    MODE_OFF = 0,          // Выключено
    MODE_COOL = 1,         // Охлаждение
    MODE_HEAT = 2,         // Отопление
    MODE_AUTO = 3,         // Авторегулировка
    MODE_DRY = 4,          // Сушка
    MODE_FAN = 5,          // Вентилятор
    MODE_SLEEP = 6,        // Сон
    MODE_TURBO = 7,        // Турбо
    // PRESET modes would be 8-23 (PRESET_1 to PRESET_16)
} midea_mode_t;

// MideaUART Control structure (based on protocol.md documentation)
typedef struct {
    uint8_t mode;           // AC mode (midea_mode_t)
    int16_t target_temp;    // Temperature * 100 (for 0.01°C resolution)
    uint8_t mode_change;    // Boolean flag (0 or 1)
    uint8_t temp_change;    // Boolean flag (0 or 1)
    uint16_t pwm_arg;       // PWM argument for fan speed
    uint8_t power_state;    // ON/OFF (0 or 1)
    int16_t presets;        // Preset configuration
} midea_control_t;

// MideaUART Status structure (for decoding responses from AC)
typedef struct {
    uint8_t mode;           // Current AC mode
    int16_t indoor_temp;    // Current indoor temperature * 100
    int16_t target_temp;    // Current target temperature * 100
    uint8_t power_state;    // Current power state
    uint8_t fan_speed;      // Current fan speed
    uint8_t error_code;     // Error code from AC
    uint16_t alarm_mask;    // Alarm mask for hardware failures
} midea_status_t;

// Function prototypes for MideaUART protocol handling
void midea_control_init(midea_control_t *control);
void midea_control_set_mode(midea_control_t *control, midea_mode_t mode);
void midea_control_set_temperature(midea_control_t *control, float temperature_celsius);
void midea_control_set_power(midea_control_t *control, bool power_on);
void midea_control_set_fan_speed(midea_control_t *control, uint8_t speed);
void midea_control_set_preset(midea_control_t *control, int16_t preset);

// Protocol encoding and decoding
size_t midea_protocol_encode(const midea_control_t *control, uint8_t *buffer, size_t buffer_size);
bool midea_protocol_decode(const uint8_t *buffer, size_t buffer_size, midea_status_t *status);

// Timing control functions
void midea_protocol_delay_ms(uint32_t ms);
bool midea_protocol_is_timeout(uint32_t start_time, uint32_t timeout_ms);

#endif // MIDEA_PROTOCOL_H