/*
 * harakirid — SI Core bridge daemon
 *
 * Userspace daemon connecting the Living Engine to the Harakiri kernel.
 * Reads /proc/harakiri/status, writes tag/untag/mode, exposes a Unix
 * socket for control.
 *
 * Protocol (text, newline-terminated, over Unix socket):
 *   TAG <pid> <agent>     - tag PID to agent (name or id)
 *   UNTAG <pid>           - untag PID
 *   MODE <name>           - set mode (phone/gaming)
 *   STATUS                - dump kernel status as JSON
 *   PING                  - liveness check, replies PONG
 *
 * Replies:
 *   OK                    - success
 *   OK <data>             - success with data (STATUS)
 *   ERR <reason>          - failure
 *
 * Build: gcc -o harakirid harakirid.c -Wall -Wextra
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <time.h>
#include <signal.h>

/* Configurable paths (env override for testing) */
static const char *proc_base;
static const char *sock_path;

#define MAX_AGENTS 16
#define MAX_LINE 1024
#define MAX_QUEUED 64

/* Agent resolved from /proc/harakiri/status */
struct hk_agent {
    int id;
    char name[32];
    char role[32];
};

/* Queued action for split-brain */
struct queued_action {
    char cmd[MAX_LINE];
    time_t queued_at;
};

static struct hk_agent agents[MAX_AGENTS];
static int n_agents = 0;
static struct queued_action queue[MAX_QUEUED];
static int q_head = 0, q_tail = 0, q_count = 0;
static volatile int running = 1;
static int kernel_ok = 1; /* false when /proc writes fail */

/* ── logging ── */
#define LOG(fmt, ...) do { \
    time_t _t = time(NULL); \
    char _tb[32]; strftime(_tb, sizeof(_tb), "%H:%M:%S", localtime(&_t)); \
    fprintf(stderr, "[%s] harakirid: " fmt "\n", _tb, ##__VA_ARGS__); \
} while(0)

/* ── proc helpers ── */
static void proc_path(char *buf, size_t n, const char *leaf) {
    snprintf(buf, n, "%s/%s", proc_base, leaf);
}

static int proc_write(const char *leaf, const char *data) {
    char path[256];
    proc_path(path, sizeof(path), leaf);
    int fd = open(path, O_WRONLY);
    if (fd < 0) {
        if (kernel_ok) {
            LOG("kernel unreachable writing %s: %s — entering split-brain",
                leaf, strerror(errno));
            kernel_ok = 0;
        }
        return -1;
    }
    ssize_t w = write(fd, data, strlen(data));
    close(fd);
    if (w < 0) {
        if (kernel_ok) {
            LOG("kernel write failed %s: %s — split-brain", leaf, strerror(errno));
            kernel_ok = 0;
        }
        return -1;
    }
    if (!kernel_ok) {
        LOG("kernel reachable again — exiting split-brain");
        kernel_ok = 1;
    }
    return 0;
}

static int proc_read(const char *leaf, char *buf, size_t n) {
    char path[256];
    proc_path(path, sizeof(path), leaf);
    int fd = open(path, O_RDONLY);
    if (fd < 0) return -1;
    ssize_t r = read(fd, buf, n - 1);
    close(fd);
    if (r < 0) return -1;
    buf[r] = '\0';
    return (int)r;
}

/* ── agent resolution ── */
static int resolve_agent(const char *name_or_id) {
    /* Try numeric first */
    char *end;
    long id = strtol(name_or_id, &end, 10);
    if (*end == '\0' && id > 0 && id <= n_agents) return (int)id;

    /* Then by name */
    for (int i = 0; i < n_agents; i++) {
        if (strcasecmp(agents[i].name, name_or_id) == 0)
            return agents[i].id;
    }
    return -1;
}

static void refresh_agents(void) {
    char buf[4096];
    if (proc_read("status", buf, sizeof(buf)) < 0) {
        if (kernel_ok) {
            LOG("cannot read status — split-brain");
            kernel_ok = 0;
        }
        return;
    }
    if (!kernel_ok) {
        LOG("kernel reachable — exiting split-brain");
        kernel_ok = 1;
    }

    /* Parse lines like: "  1 vera       role=vera ..." */
    n_agents = 0;
    char *line = strtok(buf, "\n");
    while (line && n_agents < MAX_AGENTS) {
        int id;
        char name[32], role[32];
        if (sscanf(line, "%d %31s role=%31s", &id, name, role) == 3) {
            agents[n_agents].id = id;
            strncpy(agents[n_agents].name, name, sizeof(agents[0].name) - 1);
            strncpy(agents[n_agents].role, role, sizeof(agents[0].role) - 1);
            n_agents++;
        }
        line = strtok(NULL, "\n");
    }
    LOG("resolved %d agents", n_agents);
}

/* ── action queue (split-brain) ── */
static void queue_action(const char *cmd) {
    if (q_count >= MAX_QUEUED) {
        LOG("queue full, dropping oldest");
        q_head = (q_head + 1) % MAX_QUEUED;
        q_count--;
    }
    strncpy(queue[q_tail].cmd, cmd, MAX_LINE - 1);
    queue[q_tail].queued_at = time(NULL);
    q_tail = (q_tail + 1) % MAX_QUEUED;
    q_count++;
    LOG("queued (%d pending): %s", q_count, cmd);
}

static void drain_queue(void) {
    while (q_count > 0 && kernel_ok) {
        const char *cmd = queue[q_head].cmd;
        /* Re-dispatch through proc_write path */
        char data[MAX_LINE];
        if (sscanf(cmd, "TAG %*d %*s") >= 0) {
            /* Reconstruct: cmd is "TAG <pid> <agent>" */
            int pid, agent;
            char agent_name[32];
            if (sscanf(cmd, "TAG %d %31s", &pid, agent_name) == 2) {
                agent = resolve_agent(agent_name);
                if (agent > 0) {
                    snprintf(data, sizeof(data), "%d %d", pid, agent);
                    if (proc_write("tag", data) == 0) {
                        LOG("replayed: %s", cmd);
                        q_head = (q_head + 1) % MAX_QUEUED;
                        q_count--;
                        continue;
                    }
                }
            }
            break; /* still failing, stop */
        } else if (strncmp(cmd, "MODE ", 5) == 0) {
            if (proc_write("mode", cmd + 5) == 0) {
                LOG("replayed: %s", cmd);
                q_head = (q_head + 1) % MAX_QUEUED;
                q_count--;
                continue;
            }
            break;
        } else {
            /* UNTAG or unknown — drop */
            q_head = (q_head + 1) % MAX_QUEUED;
            q_count--;
        }
    }
}

/* ── command handlers ── */
static void handle_tag(int cfd, const char *args) {
    int pid;
    char agent_name[32];
    if (sscanf(args, "%d %31s", &pid, agent_name) != 2 || pid <= 0) {
        dprintf(cfd, "ERR bad args (want: TAG <pid> <agent>)\n");
        return;
    }
    int agent = resolve_agent(agent_name);
    if (agent < 0) {
        dprintf(cfd, "ERR unknown agent '%s'\n", agent_name);
        return;
    }
    char data[64];
    snprintf(data, sizeof(data), "%d %d", pid, agent);
    if (proc_write("tag", data) == 0) {
        LOG("tagged pid %d -> agent %d (%s)", pid, agent, agent_name);
        dprintf(cfd, "OK\n");
    } else {
        char qcmd[MAX_LINE];
        snprintf(qcmd, sizeof(qcmd), "TAG %d %s", pid, agent_name);
        queue_action(qcmd);
        dprintf(cfd, "OK queued (split-brain)\n");
    }
}

static void handle_untag(int cfd, const char *args) {
    int pid;
    if (sscanf(args, "%d", &pid) != 1 || pid <= 0) {
        dprintf(cfd, "ERR bad args (want: UNTAG <pid>)\n");
        return;
    }
    char data[32];
    snprintf(data, sizeof(data), "%d", pid);
    if (proc_write("untag", data) == 0) {
        LOG("untagged pid %d", pid);
        dprintf(cfd, "OK\n");
    } else {
        char qcmd[MAX_LINE];
        snprintf(qcmd, sizeof(qcmd), "UNTAG %d", pid);
        queue_action(qcmd);
        dprintf(cfd, "OK queued (split-brain)\n");
    }
}

static void handle_mode(int cfd, const char *args) {
    char mode[32];
    if (sscanf(args, "%31s", mode) != 1) {
        dprintf(cfd, "ERR bad args (want: MODE <name>)\n");
        return;
    }
    /* Validate mode name */
    if (strcmp(mode, "phone") != 0 && strcmp(mode, "gaming") != 0) {
        dprintf(cfd, "ERR unknown mode '%s' (want phone|gaming)\n", mode);
        return;
    }
    if (proc_write("mode", mode) == 0) {
        LOG("mode -> %s", mode);
        dprintf(cfd, "OK\n");
    } else {
        char qcmd[MAX_LINE];
        snprintf(qcmd, sizeof(qcmd), "MODE %s", mode);
        queue_action(qcmd);
        dprintf(cfd, "OK queued (split-brain)\n");
    }
}

static void handle_status(int cfd) {
    char buf[4096];
    if (proc_read("status", buf, sizeof(buf)) < 0) {
        dprintf(cfd, "ERR kernel unreachable (split-brain, %d queued)\n", q_count);
        return;
    }
    /* Wrap in simple framing */
    dprintf(cfd, "OK\n%s\nEND\n", buf);
}

static void handle_client(int cfd) {
    char line[MAX_LINE];
    FILE *f = fdopen(cfd, "r+");
    if (!f) { close(cfd); return; }

    while (fgets(line, sizeof(line), f)) {
        /* Strip newline */
        line[strcspn(line, "\r\n")] = '\0';
        if (!*line) continue;

        if (strncmp(line, "TAG ", 4) == 0) {
            handle_tag(cfd, line + 4);
        } else if (strncmp(line, "UNTAG ", 6) == 0) {
            handle_untag(cfd, line + 6);
        } else if (strncmp(line, "MODE ", 5) == 0) {
            handle_mode(cfd, line + 5);
        } else if (strcmp(line, "STATUS") == 0) {
            handle_status(cfd);
        } else if (strcmp(line, "PING") == 0) {
            dprintf(cfd, "PONG\n");
        } else if (strcmp(line, "QUIT") == 0) {
            break;
        } else {
            dprintf(cfd, "ERR unknown command\n");
        }
        fflush(f);
    }
    fclose(f); /* closes cfd */
}

/* ── Vera rules (package → agent, mode) ── */
struct vera_rule {
    const char *pattern;
    const char *agent;
    const char *mode;
};

static struct vera_rule vera_rules[] = {
    { "steam",    "brood-00", "gaming" },
    { "game",     "brood-00", "gaming" },
    { "dialer",   "mira",     "phone"  },
    { "mms",      "mira",     "phone"  },
    { "camera",   "paintr",   "phone"  },
    { NULL, NULL, NULL },
};

/* Classify a package name → (agent, mode). Returns 0 if matched. */
int vera_classify(const char *pkg, const char **agent, const char **mode) {
    for (int i = 0; vera_rules[i].pattern; i++) {
        if (strstr(pkg, vera_rules[i].pattern)) {
            *agent = vera_rules[i].agent;
            *mode = vera_rules[i].mode;
            return 0;
        }
    }
    return -1;
}

/* ── main ── */
static void on_signal(int sig) {
    (void)sig;
    running = 0;
}

int main(int argc, char **argv) {
    proc_base = getenv("HARAKIRI_PROC") ?: "/proc/harakiri";
    sock_path = getenv("HARAKIRI_SOCK") ?: "/dev/socket/harakiri";

    /* Allow CLI override for testing */
    for (int i = 1; i < argc; i++) {
        if (strncmp(argv[i], "--proc=", 7) == 0) proc_base = argv[i] + 7;
        else if (strncmp(argv[i], "--sock=", 7) == 0) sock_path = argv[i] + 7;
    }

    signal(SIGINT, on_signal);
    signal(SIGTERM, on_signal);

    LOG("starting, proc=%s sock=%s", proc_base, sock_path);

    /* Initial agent resolution */
    refresh_agents();
    if (n_agents == 0) {
        LOG("warning: no agents resolved (kernel may be unreachable)");
    }

    /* Create Unix socket */
    int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sfd < 0) { perror("socket"); return 1; }

    struct sockaddr_un addr = { .sun_family = AF_UNIX };
    strncpy(addr.sun_path, sock_path, sizeof(addr.sun_path) - 1);
    unlink(sock_path); /* remove stale */

    if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
        perror("bind"); return 1;
    }
    if (listen(sfd, 8) < 0) { perror("listen"); return 1; }
    chmod(sock_path, 0666);

    LOG("listening on %s", sock_path);

    /* Main loop */
    while (running) {
        fd_set rfds;
        FD_ZERO(&rfds);
        FD_SET(sfd, &rfds);
        struct timeval tv = { .tv_sec = 5, .tv_usec = 0 };

        int r = select(sfd + 1, &rfds, NULL, NULL, &tv);
        if (r < 0) {
            if (errno == EINTR) continue;
            perror("select"); break;
        }
        if (r == 0) {
            /* Periodic: refresh agents, drain queue */
            refresh_agents();
            if (q_count > 0 && kernel_ok) drain_queue();
            continue;
        }
        int cfd = accept(sfd, NULL, NULL);
        if (cfd < 0) { perror("accept"); continue; }
        handle_client(cfd);
    }

    LOG("shutting down (%d actions still queued)", q_count);
    close(sfd);
    unlink(sock_path);
    return 0;
}
