/* shkd-style configuration for Windows RegisterHotKey.
 * Syntax inspired by https://github.com/baskerville/shkd (Bastien Dejean).
 * This is an independent Win32 implementation, not vendored shkd code.
 */
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <string.h>

enum { SHELL_COMMAND, PLUGIN, TOGGLE_EXPLORER, CLOSE_WINDOW, FORCE_CLOSE_WINDOW, QUIT, TEST };

typedef struct {
    unsigned int mod, key;
    char *command;
    int action;
    char *plugin_name, *plugin_action, *plugin_args;
    size_t plugin_index;
} Binding;

static Binding *bindings;
static size_t binding_count;

static char *trim(char *s) {
    while (isspace((unsigned char)*s)) s++;
    char *end = s + strlen(s);
    while (end > s && isspace((unsigned char)end[-1])) *--end = '\0';
    return s;
}

static char *copy_string(const char *s) {
    size_t n = strlen(s) + 1;
    char *copy = malloc(n);
    if (copy) memcpy(copy, s, n);
    return copy;
}

static int same(const char *a, const char *b) {
    while (*a && *b && tolower((unsigned char)*a) == tolower((unsigned char)*b)) a++, b++;
    return *a == *b;
}

static unsigned int key_name(const char *name) {
    if (name[0] && !name[1]) {
        int c = toupper((unsigned char)name[0]);
        if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return c;
    }
    struct { const char *name; unsigned int code; } names[] = {
        {"return", VK_RETURN}, {"enter", VK_RETURN}, {"tab", VK_TAB},
        {"space", VK_SPACE}, {"spacebar", VK_SPACE}, {"escape", VK_ESCAPE},
        {"esc", VK_ESCAPE}, {"backspace", VK_BACK}, {"delete", VK_DELETE},
        {"insert", VK_INSERT}, {"home", VK_HOME}, {"end", VK_END},
        {"pageup", VK_PRIOR}, {"pagedown", VK_NEXT}, {"left", VK_LEFT},
        {"right", VK_RIGHT}, {"up", VK_UP}, {"down", VK_DOWN},
        {"printscreen", VK_SNAPSHOT}, {"pause", VK_PAUSE},
        {"minus", VK_OEM_MINUS}, {"equal", VK_OEM_PLUS},
        {"comma", VK_OEM_COMMA}, {"period", VK_OEM_PERIOD},
        {"slash", VK_OEM_2}, {"semicolon", VK_OEM_1},
        {"apostrophe", VK_OEM_7}, {"backslash", VK_OEM_5},
        {"bracketleft", VK_OEM_4}, {"bracketright", VK_OEM_6},
        {"grave", VK_OEM_3}
    };
    for (size_t i = 0; i < sizeof names / sizeof names[0]; i++)
        if (same(name, names[i].name)) return names[i].code;
    if (tolower((unsigned char)name[0]) == 'f' && isdigit((unsigned char)name[1])) {
        char *end;
        long n = strtol(name + 1, &end, 10);
        if (!*end && n >= 1 && n <= 24) return VK_F1 + n - 1;
    }
    if (name[0] == '=') {
        char *end;
        long n = strtol(name + 1, &end, 10);
        if (end != name + 1 && !*end && n > 0 && n <= 255) return (unsigned int)n;
    }
    return 0;
}

static int parse_hotkey(char *line, unsigned int *mod, unsigned int *key) {
    *mod = *key = 0;
    for (char *token = strtok(line, " +\t\r\n"); token; token = strtok(NULL, " +\t\r\n")) {
        if (same(token, "alt")) *mod |= MOD_ALT;
        else if (same(token, "ctrl") || same(token, "control")) *mod |= MOD_CONTROL;
        else if (same(token, "shift")) *mod |= MOD_SHIFT;
        else if (same(token, "meta") || same(token, "super") || same(token, "win")) *mod |= MOD_WIN;
        else {
            unsigned int code = key_name(token);
            if (!code || *key) return 0;
            *key = code;
        }
    }
    return *key != 0;
}

static int plugin_char(unsigned char c) {
    return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
           (c >= '0' && c <= '9') || c == '-' || c == '_';
}

static int parse_action(const char *command) {
    if (command[0] != ':') return SHELL_COMMAND;
    if (same(command, ":toggle-explorer")) return TOGGLE_EXPLORER;
    if (same(command, ":close-window")) return CLOSE_WINDOW;
    if (same(command, ":force-close-window")) return FORCE_CLOSE_WINDOW;
    if (same(command, ":quit")) return QUIT;
    if (same(command, ":test")) return TEST;
    const char *name = command + 1;
    const char *space = strpbrk(name, " \t");
    if (!space || space == name || space - name > 63) return -1;
    const char *action = space + strspn(space, " \t");
    const char *end = strpbrk(action, " \t");
    if (!end) end = action + strlen(action);
    if (end == action || end - action > 63) return -1;
    for (const char *p = name; p < space; p++)
        if (!plugin_char((unsigned char)*p)) return -1;
    for (const char *p = action; p < end; p++)
        if (!plugin_char((unsigned char)*p)) return -1;
    return PLUGIN;
}

static void free_bindings(void) {
    for (size_t i = 0; i < binding_count; i++) free(bindings[i].command);
    free(bindings);
    bindings = NULL;
    binding_count = 0;
}

/* Consecutive indented lines for a hotkey run in order. The last definition
 * of a hotkey replaces its previous command group. */
static int load_config(const char *path) {
    FILE *file = fopen(path, "r");
    if (!file) {
        fprintf(stderr, "dwhkd: cannot open %s: %s\n", path, strerror(errno));
        return 0;
    }
    char line[8192];
    unsigned int mod = 0, key = 0;
    int has_command = 0;
    size_t lineno = 0;
    int ok = 1;
    while (fgets(line, sizeof line, file)) {
        lineno++;
        if (!strchr(line, '\n') && !feof(file)) {
            fprintf(stderr, "%s:%zu: line too long\n", path, lineno);
            int c;
            while ((c = fgetc(file)) != '\n' && c != EOF) {}
            key = 0; has_command = 0; ok = 0;
            continue;
        }
        int indented = isspace((unsigned char)line[0]);
        char *value = trim(line);
        if (!*value || *value == '#') continue;
        if (!indented) {
            if (key && !has_command) {
                fprintf(stderr, "%s:%zu: hotkey without command\n", path, lineno - 1);
                ok = 0;
            }
            if (!parse_hotkey(value, &mod, &key)) {
                fprintf(stderr, "%s:%zu: unsupported hotkey\n", path, lineno);
                key = 0; ok = 0;
            }
            has_command = 0;
        } else if (key) {
            if (strncmp(value, "->[", 3) == 0) {
                fprintf(stderr, "%s:%zu: modes are not supported\n", path, lineno);
                key = 0; ok = 0;
                continue;
            }
            int action = parse_action(value);
            if (action < 0) {
                fprintf(stderr, "%s:%zu: unknown action\n", path, lineno);
                key = 0; ok = 0;
                continue;
            }
            if (binding_count >= INT_MAX) { ok = 0; break; }
            char *command = copy_string(value);
            Binding *next = command ? realloc(bindings, (binding_count + 1) * sizeof *bindings) : NULL;
            if (!next) { free(command); ok = 0; break; }
            bindings = next;
            if (!has_command) {
                /* The last hotkey definition replaces its entire earlier group. */
                for (size_t i = 0; i < binding_count;) {
                    if (bindings[i].key == key && bindings[i].mod == mod) {
                        free(bindings[i].command);
                        memmove(&bindings[i], &bindings[i + 1],
                            (binding_count - i - 1) * sizeof *bindings);
                        binding_count--;
                    } else i++;
                }
            }
            Binding binding = {.mod = mod, .key = key, .command = command, .action = action};
            if (action == PLUGIN) {
                char *name = command + 1;
                char *action_name = strpbrk(name, " \t");
                *action_name++ = '\0';
                while (*action_name == ' ' || *action_name == '\t') action_name++;
                char *args = strpbrk(action_name, " \t");
                if (args) {
                    *args++ = '\0';
                    while (*args == ' ' || *args == '\t') args++;
                }
                binding.plugin_name = name;
                binding.plugin_action = action_name;
                binding.plugin_args = args ? args : "";
            }
            bindings[binding_count++] = binding;
            has_command = 1;
        } else {
            fprintf(stderr, "%s:%zu: command without hotkey\n", path, lineno);
            ok = 0;
        }
    }
    if (ferror(file)) ok = 0;
    if (key && !has_command) { fprintf(stderr, "%s: hotkey without command\n", path); ok = 0; }
    fclose(file);
    if (!ok) free_bindings();
    return ok;
}
