/*
 * kl_session.h
 * Session layer: 5-baud init, handshake, ident stream, session lifecycle.
 */

#ifndef KL_SESSION_H
#define KL_SESSION_H

#include "kl_protocol.h"

/* ================================================================
 * Session states
 * ================================================================ */
typedef enum {
    KL_SESS_IDLE,

    /* 5-baud address reception */
    KL_SESS_5BAUD_SAMPLING,
    KL_SESS_5BAUD_DONE,

    /* Handshake: sync + keywords */
    KL_SESS_HS_SYNC,
    KL_SESS_HS_SYNC_WAIT,
    KL_SESS_HS_KW_LSB,
    KL_SESS_HS_KW_LSB_WAIT,
    KL_SESS_HS_KW_MSB,
    KL_SESS_HS_KW_MSB_WAIT,
    KL_SESS_HS_WAIT_ACK,

    /* Identification stream */
    KL_SESS_IDENT_SEND,
    KL_SESS_IDENT_WAIT_TX,
    KL_SESS_IDENT_WAIT_ACK,
    KL_SESS_IDENT_FINAL_ACK,
    KL_SESS_IDENT_FINAL_WAIT,

    /* Active session */
    KL_SESS_READY,
    KL_SESS_CMD_RX,
    KL_SESS_CMD_DISPATCH,
    KL_SESS_CMD_RESPONSE,
    KL_SESS_CMD_NAK_WAIT,  /* Sending NAK after invalid packet */

    /* Teardown */
    KL_SESS_TERMINATE
} KL_SessionState;

/* ================================================================
 * Session context
 * ================================================================ */
typedef struct {
    KL_SessionState state;

    /* 5-baud sampling */
    uint8_t  five_bit_index;
    uint8_t  five_byte;
    uint8_t  five_active;

    /* Handshake */
    uint8_t  hs_retry_count;
    uint32_t hs_next_tick;

    /* Identification stream */
    uint8_t  ident_buf[KL_IDENT_BUF_SIZE];
    uint8_t  ident_len;
    uint8_t  ident_offset;
    uint8_t  ident_chunk_len;   /* Current chunk size being sent */

    /* Session keepalive */
    uint32_t session_deadline;

    /* Connection status: 0=idle, 1=connecting, 2=active */
    volatile uint8_t connection_status;

    /* Signal from app layer that End command was handled */
    uint8_t  end_requested;
} KL_Session;

/* ================================================================
 * API
 * ================================================================ */
void    KL_Session_Init(void);
void    KL_Session_Service(void);
uint8_t KL_Session_GetStatus(void);
void    KL_Session_RequestEnd(void);    /* Called by app on CMD_End */
void    KL_Session_Kick(void);          /* Extend session deadline  */

/* ISR callbacks */
void    KL_Session_OnExtiRxFalling(void);
void    KL_Session_OnTim17Elapsed(void);

#endif /* KL_SESSION_H */
