// Copyright (C) 2026 Actia Nordic AB. All rights reserved.

#include <actia/actia.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>

#include "ipc.h"

#define IPC_MSG_BUF_SIZE 256
#define IPC_OUTBOX_SIZE  512
#define IPC_INBOX_SIZE   512

A_IPC_STATIC_BUFFERS_BYTES(ipc_buffers, IPC_INBOX_SIZE, IPC_OUTBOX_SIZE);
A_IPC_STATIC_MSG(msg, IPC_MSG_BUF_SIZE);

typedef enum {
    IPC_PENDING_REQUEST_NONE = 0,
    IPC_PENDING_REQUEST_OPEN_SESSION,
    IPC_PENDING_REQUEST_LED_SET,
} ipc_pending_request_t;

typedef struct {
    bool session_open;
} ipc_state_t;

static a_ipc_handle *a_ipc;
static int retry_timer_fd = -1;
static ipc_state_t ipc_state = {
    .session_open = false,
};
static ipc_pending_request_t pending_request = IPC_PENDING_REQUEST_NONE;
static uint8_t pending_led_state = LED_OFF;

static int retry_timer_arm(uint32_t timeout)
{
    struct itimerspec ts = {0};
    ts.it_value.tv_sec = (time_t)timeout;
    return timerfd_settime(retry_timer_fd, 0, &ts, NULL);
}

static int retry_timer_disarm(void)
{
    const struct itimerspec ts = {0};
    return timerfd_settime(retry_timer_fd, 0, &ts, NULL);
}

static int ipc_mark_request_pending(ipc_pending_request_t request)
{
    pending_request = request;

    if (retry_timer_arm(1) < 0) {
        fprintf(stderr, "Couldn't arm retry timer\n");
        pending_request = IPC_PENDING_REQUEST_NONE;
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return -1;
    }

    return 0;
}

static int ipc_clear_pending_request(void)
{
    if (retry_timer_disarm() < 0) {
        fprintf(stderr, "Couldn't disarm retry timer\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return -1;
    }

    pending_request = IPC_PENDING_REQUEST_NONE;
    return 0;
}

static void ipc_handle_retry_timer_event(void)
{
    A_IPC_RESULT rc = A_IPC_RET_OK;

    switch (pending_request) {
    case IPC_PENDING_REQUEST_OPEN_SESSION:
        rc = ipc_send_open_session_req(A_SERVICE_ID_SYSTEM);
        break;
    case IPC_PENDING_REQUEST_LED_SET:
        rc = ipc_set_led(A_IPC_ENUM_LED_PIN_TYPE_GREEN, pending_led_state);
        break;
    case IPC_PENDING_REQUEST_NONE:
        return;
    }

    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to resend pending IPC request\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
    }
}

static void ipc_handle_open_session_rsp(a_ipc_msg_ipc_open_session_rsp *msg_rsp)
{
    if (pending_request != IPC_PENDING_REQUEST_OPEN_SESSION) {
        return;
    }

    if (msg_rsp->result != A_IPC_ENUM_IPC_OPEN_SESSION_RESULT_OK) {
        fprintf(stderr, "Error opening session: %d\n", msg_rsp->result);
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return;
    }

    if (ipc_clear_pending_request() < 0) {
        return;
    }

    ipc_state.session_open = true;

    A_IPC_RESULT rc = ipc_set_led(A_IPC_ENUM_LED_PIN_TYPE_GREEN, LED_ON);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Couldn't send message\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return;
    }
}

static void ipc_handle_led_set_rsp(a_ipc_msg_led_set_rsp *msg_rsp)
{
    if (pending_request != IPC_PENDING_REQUEST_LED_SET) {
        return;
    }

    if (msg_rsp->result != A_IPC_ENUM_LED_RESULT_OK) {
        fprintf(stderr, "Error lighting LED: %d\n", msg_rsp->result);
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return;
    }

    if (ipc_clear_pending_request() < 0) {
        return;
    }

    if (pending_led_state == LED_ON) {
        sleep(1);

        A_IPC_RESULT rc = ipc_set_led(A_IPC_ENUM_LED_PIN_TYPE_GREEN, LED_OFF);
        if (rc != A_IPC_RET_OK) {
            fprintf(stderr, "Couldn't send message\n");
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
            return;
        }

        return;
    }

    set_event_loop_state(EVENT_LOOP_EXIT_OK);
}

int ipc_initialize_actia_ipc(int ipc_id, int epfd)
{
    a_ipc = a_ipc_init(ipc_id, &ipc_buffers);

    if (a_ipc == NULL) {
        return -ENOMEM;
    }

    struct epoll_event ipc_events = {
        .events = EPOLLIN,
        .data.fd = a_ipc_get_fd(a_ipc),
    };

    if (epoll_ctl(epfd, EPOLL_CTL_ADD, a_ipc_get_fd(a_ipc), &ipc_events) == -1) {
        fprintf(stderr, "Error epoll_ctl ipc_fd, EPOLL_CTL_ADD: %d\n", errno);
        int saved_errno = errno;
        a_ipc_destroy(a_ipc);
        return -saved_errno;
    }

    retry_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
    if (retry_timer_fd < 0) {
        fprintf(stderr, "Couldn't create retry timer\n");
        int saved_errno = errno;
        a_ipc_destroy(a_ipc);
        return -saved_errno;
    }

    struct epoll_event retry_timer_event = {
        .events = EPOLLIN,
        .data.fd = retry_timer_fd,
    };

    if (epoll_ctl(epfd, EPOLL_CTL_ADD, retry_timer_fd, &retry_timer_event) == -1) {
        fprintf(stderr, "Error epoll_ctl retry_timer_fd, EPOLL_CTL_ADD: %d\n", errno);
        int saved_errno = errno;
        close(retry_timer_fd);
        retry_timer_fd = -1;
        a_ipc_destroy(a_ipc);
        return -saved_errno;
    }

    return a_ipc_get_fd(a_ipc);
}

A_IPC_RESULT ipc_send_open_session_req(int to)
{
    A_IPC_RESULT rc = a_ipc_init_ipc_open_session_req(msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to create open session request: %s\n", a_ipc_result_str(rc));
        return rc;
    }

    rc = a_ipc_send(a_ipc, to, msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to send open session request: %s\n", a_ipc_result_str(rc));
        return rc;
    }

    if (ipc_mark_request_pending(IPC_PENDING_REQUEST_OPEN_SESSION) < 0) {
        return A_IPC_RET_ERROR;
    }

    return A_IPC_RET_OK;
}

bool ipc_handle_actia_ipc_event(struct epoll_event *event)
{
    if ((event->events & EPOLLIN) && event->data.fd == retry_timer_fd) {
        uint64_t timers = 0;
        ssize_t read_size = read(retry_timer_fd, &timers, sizeof(timers));
        if (read_size != (ssize_t)sizeof(timers)) {
            fprintf(stderr, "Failed to read retry timer\n");
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
            return true;
        }

        ipc_handle_retry_timer_event();
        return true;
    }

    if (!(event->events & EPOLLIN) || event->data.fd != a_ipc_get_fd(a_ipc)) {
        return false;
    }

    int from = -1;
    A_IPC_RESULT rc = a_ipc_recv(a_ipc, &from, msg);

    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to fetch message\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return true;
    }

    (void)from;

    switch (msg->info.type) {
    case A_IPC_MSG_IPC_OPEN_SESSION_RSP:
        ipc_handle_open_session_rsp(&msg->ipc_open_session_rsp);
        break;
    case A_IPC_MSG_LED_SET_RSP:
        ipc_handle_led_set_rsp(&msg->led_set_rsp);
        break;
    default:
        fprintf(stderr, "Unrecognized response received\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        break;
    }

    return true;
}

A_IPC_RESULT ipc_set_led(a_ipc_enum_led_pin_type led, uint8_t state)
{
    A_IPC_RESULT rc = a_ipc_init_led_set_req(msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Could not init A_IPC_LED_SET_REQ message %d\n", rc);
        return rc;
    }

    msg->led_set_req.pin = led;
    msg->led_set_req.value = state;

    pending_led_state = state;

    rc = a_ipc_send(a_ipc, A_SERVICE_ID_SYSTEM, msg);
    if (rc != A_IPC_RET_OK) {
        return rc;
    }

    if (ipc_mark_request_pending(IPC_PENDING_REQUEST_LED_SET) < 0) {
        return A_IPC_RET_ERROR;
    }

    return A_IPC_RET_OK;
}

void ipc_destroy_actia_ipc(void)
{
    if (retry_timer_fd >= 0) {
        close(retry_timer_fd);
        retry_timer_fd = -1;
    }

    if (a_ipc != NULL) {
        a_ipc_destroy(a_ipc);
        a_ipc = NULL;
    }

    pending_request = IPC_PENDING_REQUEST_NONE;
    ipc_state.session_open = false;
}
