// 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 <string.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
#define NUM_LEDS         3

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_SYSTEM_SESSION,
    IPC_PENDING_REQUEST_OPEN_LOCATION_SESSION,
    IPC_PENDING_REQUEST_LED_SET,
    IPC_PENDING_REQUEST_LOCATION_REQUEST,
    IPC_PENDING_REQUEST_LOCATION_SUBSCRIBE,
} ipc_pending_request_t;

typedef struct {
    bool system_session_open;
    bool location_session_open;
    int ticks;
    struct timespec last_location_update_time;
} ipc_state_t;

static a_ipc_handle *a_ipc;
static int sequence_timer_fd = -1;
static int retry_timer_fd = -1;
static ipc_state_t ipc_state = {
    .system_session_open = false,
    .location_session_open = false,
    .ticks = 0,
    .last_location_update_time = {0},
};

static ipc_pending_request_t pending_request = IPC_PENDING_REQUEST_NONE;
static bool location_requested = false;
static bool location_subscribed = false;
static size_t pending_led_index = 0;
static a_ipc_enum_led_pin_type pending_led = A_IPC_ENUM_LED_PIN_TYPE_RED;
static uint8_t pending_led_state = LED_OFF;
static bool sequence_timer_started = false;
static bool stop_requested = false;
static uint8_t desired_led_states[NUM_LEDS] = {LED_OFF};
static uint8_t actual_led_states[NUM_LEDS] = {LED_OFF};
static a_ipc_enum_led_pin_type leds[NUM_LEDS] = {
    A_IPC_ENUM_LED_PIN_TYPE_RED,
    A_IPC_ENUM_LED_PIN_TYPE_GREEN,
    A_IPC_ENUM_LED_PIN_TYPE_BLUE,
};

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 sequence_timer_arm(uint32_t start_time, uint32_t interval)
{
    struct itimerspec ts = {0};
    ts.it_value.tv_sec = (time_t)start_time;
    ts.it_interval.tv_sec = (time_t)interval;
    return timerfd_settime(sequence_timer_fd, 0, &ts, NULL);
}

static int sequence_timer_disarm(void)
{
    const struct itimerspec ts = {0};
    return timerfd_settime(sequence_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_schedule_next_request(void)
{
    A_IPC_RESULT rc = A_IPC_RET_OK;
    bool sent_led_update = false;

    if (pending_request != IPC_PENDING_REQUEST_NONE) {
        return;
    }

    if (!ipc_state.system_session_open) {
        rc = ipc_send_open_session_req(A_SERVICE_ID_SYSTEM);
    } else {
        if (!sequence_timer_started) {
            if (sequence_timer_arm(1, 1) < 0) {
                fprintf(stderr, "Couldn't arm timer\n");
                set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
                return;
            }

            sequence_timer_started = true;
        }

        if (!ipc_state.location_session_open) {
            rc = ipc_send_open_session_req(A_SERVICE_ID_LOCATION);
        } else if (!location_requested) {
            rc = ipc_location_request();
        } else if (!location_subscribed) {
            rc = ipc_location_subscribe();
        } else {
            for (size_t led_index = 0; led_index < NUM_LEDS; ++led_index) {
                if (desired_led_states[led_index] == actual_led_states[led_index]) {
                    continue;
                }

                rc = ipc_set_led(leds[led_index], desired_led_states[led_index]);
                sent_led_update = true;
                break;
            }

            if (sent_led_update) {
                if (rc != A_IPC_RET_OK) {
                    fprintf(stderr, "Couldn't send message\n");
                    set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
                }

                return;
            }

            if (stop_requested) {
                set_event_loop_state(EVENT_LOOP_EXIT_OK);
            }

            return;
        }
    }

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

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

    switch (pending_request) {
    case IPC_PENDING_REQUEST_OPEN_SYSTEM_SESSION:
        rc = ipc_send_open_session_req(A_SERVICE_ID_SYSTEM);
        break;
    case IPC_PENDING_REQUEST_OPEN_LOCATION_SESSION:
        rc = ipc_send_open_session_req(A_SERVICE_ID_LOCATION);
        break;
    case IPC_PENDING_REQUEST_LED_SET:
        rc = ipc_set_led(pending_led, pending_led_state);
        break;
    case IPC_PENDING_REQUEST_LOCATION_REQUEST:
        rc = ipc_location_request();
        break;
    case IPC_PENDING_REQUEST_LOCATION_SUBSCRIBE:
        rc = ipc_location_subscribe();
        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,
                                        int from)
{
    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 ((pending_request == IPC_PENDING_REQUEST_OPEN_SYSTEM_SESSION) && (from == A_SERVICE_ID_SYSTEM)) {
        ipc_state.system_session_open = true;
    } else if ((pending_request == IPC_PENDING_REQUEST_OPEN_LOCATION_SESSION) &&
               (from == A_SERVICE_ID_LOCATION)) {
        ipc_state.location_session_open = true;
    } else {
        return;
    }

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

    ipc_schedule_next_request();
}

static void ipc_handle_led_set_rsp(a_ipc_msg_led_set_rsp *msg_rsp)
{
    size_t completed_led_index = pending_led_index;
    uint8_t completed_led_state = pending_led_state;

    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;
    }

    actual_led_states[completed_led_index] = completed_led_state;
    ipc_schedule_next_request();
}

static void ipc_handle_location_request_rsp(void)
{
    if (pending_request != IPC_PENDING_REQUEST_LOCATION_REQUEST) {
        return;
    }

    location_requested = true;
    if (ipc_clear_pending_request() < 0) {
        return;
    }

    ipc_schedule_next_request();
}

static void ipc_handle_location_subscribe_rsp(void)
{
    if (pending_request != IPC_PENDING_REQUEST_LOCATION_SUBSCRIBE) {
        return;
    }

    location_subscribed = true;
    if (ipc_clear_pending_request() < 0) {
        return;
    }

    printf("Subscribed to location updates\n");
    ipc_schedule_next_request();
}

static void ipc_handle_location_publish_ind(a_ipc_msg_location_publish_ind *msg_ind)
{
    clock_gettime(CLOCK_MONOTONIC, &ipc_state.last_location_update_time);
    printf("Longitude: %d, Latitude: %d, Altitude: %d\n",
           msg_ind->longitude,
           msg_ind->latitude,
           msg_ind->altitude);

    desired_led_states[1] = LED_ON;
    ipc_schedule_next_request();
}

static void ipc_handle_sequence_timer_event(const led_example_options_t *params)
{
    struct timespec current_time;
    struct timespec diff_time;

    clock_gettime(CLOCK_MONOTONIC, &current_time);

    diff_time.tv_sec = current_time.tv_sec - ipc_state.last_location_update_time.tv_sec;
    diff_time.tv_nsec = current_time.tv_nsec - ipc_state.last_location_update_time.tv_nsec;

    if (diff_time.tv_nsec < 0) {
        diff_time.tv_sec -= 1;
        diff_time.tv_nsec += 1000000000;
    }

    desired_led_states[0] = (desired_led_states[0] == LED_ON) ? LED_OFF : LED_ON;

    if (diff_time.tv_sec > 5) {
        desired_led_states[1] = LED_OFF;
    }

    ipc_state.ticks += 1;
    if ((ipc_state.ticks >= params->max_ticks) && (params->max_ticks != 0)) {
        stop_requested = true;
        if (sequence_timer_disarm() < 0) {
            fprintf(stderr, "Couldn't disarm timer\n");
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
            return;
        }
    }

    ipc_schedule_next_request();
}

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;
    }

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

    struct epoll_event timer_event = {
        .events = EPOLLIN,
        .data.fd = sequence_timer_fd,
    };

    if (epoll_ctl(epfd, EPOLL_CTL_ADD, sequence_timer_fd, &timer_event) == -1) {
        fprintf(stderr, "Error epoll_ctl sequence_timer_fd, EPOLL_CTL_ADD: %d\n", errno);
        int saved_errno = errno;
        close(sequence_timer_fd);
        sequence_timer_fd = -1;
        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 (to == A_SERVICE_ID_SYSTEM) {
        if (ipc_mark_request_pending(IPC_PENDING_REQUEST_OPEN_SYSTEM_SESSION) < 0) {
            return A_IPC_RET_ERROR;
        }
    } else if (to == A_SERVICE_ID_LOCATION) {
        if (ipc_mark_request_pending(IPC_PENDING_REQUEST_OPEN_LOCATION_SESSION) < 0) {
            return A_IPC_RET_ERROR;
        }
    } else {
        return A_IPC_RET_INVALID_ARGUMENT;
    }

    return A_IPC_RET_OK;
}

A_IPC_RESULT ipc_location_request(void)
{
    static char *user = "led-example";

    A_IPC_RESULT rc = a_ipc_init_location_request_req(msg, 15);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Could not init A_IPC_MSG_LOCATION_REQUEST_REQ message %d\n", rc);
        return rc;
    }

    msg->location_request_req.user.value = user;
    msg->location_request_req.user.length = strlen(user);

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

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

    return A_IPC_RET_OK;
}

A_IPC_RESULT ipc_location_subscribe(void)
{
    A_IPC_RESULT rc = a_ipc_init_location_subscribe_req(msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Could not init A_IPC_MSG_LOCATION_SUBSCRIBE_REQ message %d\n", rc);
        return rc;
    }

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

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

    return A_IPC_RET_OK;
}

bool ipc_handle_actia_ipc_event(struct epoll_event *event,
                                const led_example_options_t *params)
{
    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 == sequence_timer_fd) {
        uint64_t timers = 0;
        ssize_t read_size = read(sequence_timer_fd, &timers, sizeof(timers));
        if (read_size != (ssize_t)sizeof(timers)) {
            fprintf(stderr, "Failed to read sequence timer\n");
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
            return true;
        }

        ipc_handle_sequence_timer_event(params);
        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;
    }

    switch (msg->info.type) {
    case A_IPC_MSG_IPC_OPEN_SESSION_RSP:
        ipc_handle_open_session_rsp(&msg->ipc_open_session_rsp, from);
        break;
    case A_IPC_MSG_LED_SET_RSP:
        ipc_handle_led_set_rsp(&msg->led_set_rsp);
        break;
    case A_IPC_MSG_LOCATION_REQUEST_RSP:
        ipc_handle_location_request_rsp();
        break;
    case A_IPC_MSG_LOCATION_SUBSCRIBE_RSP:
        ipc_handle_location_subscribe_rsp();
        break;
    case A_IPC_MSG_LOCATION_PUBLISH_IND:
        ipc_handle_location_publish_ind(&msg->location_publish_ind);
        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;

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

    pending_led = led;
    pending_led_state = state;
    for (size_t led_index = 0; led_index < NUM_LEDS; ++led_index) {
        if (leds[led_index] == led) {
            pending_led_index = led_index;
            break;
        }
    }

    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 (sequence_timer_fd >= 0) {
        close(sequence_timer_fd);
        sequence_timer_fd = -1;
    }

    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;
    location_requested = false;
    location_subscribed = false;
    sequence_timer_started = false;
    stop_requested = false;
    pending_led_index = 0;
    pending_led = A_IPC_ENUM_LED_PIN_TYPE_RED;
    pending_led_state = LED_OFF;
    ipc_state.system_session_open = false;
    ipc_state.location_session_open = false;
    ipc_state.ticks = 0;
    ipc_state.last_location_update_time = (struct timespec){0};
    memset(desired_led_states, LED_OFF, sizeof(desired_led_states));
    memset(actual_led_states, LED_OFF, sizeof(actual_led_states));
}
