/* config.c - Implementasi loader file konfigurasi */
#include "config.h"

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

void config_init(config *c) {
    if (c == NULL) {
        return;
    }
    c->count = 0;
}

static void strip(char *s) {
    /* Trim whitespace di kiri. */
    char *start = s;
    while (*start != '\0' && isspace((unsigned char)*start)) {
        start++;
    }
    if (start != s) {
        memmove(s, start, strlen(start) + 1);
    }
    /* Trim whitespace di kanan. */
    size_t len = strlen(s);
    while (len > 0 && isspace((unsigned char)s[len - 1])) {
        s[--len] = '\0';
    }
}

static void parse_line(char *line, config *c) {
    /* Lewati komentar dan baris kosong. */
    if (line[0] == '#' || line[0] == ';' || line[0] == '\0') {
        return;
    }
    /* Cari '=' pemisah. */
    char *eq = strchr(line, '=');
    if (eq == NULL) {
        return;
    }
    *eq = '\0';
    char *key = line;
    char *value = eq + 1;
    strip(key);
    strip(value);
    if (key[0] == '\0' || c->count >= CONFIG_ENTRIES_MAX) {
        return;
    }
    config_entry *e = &c->entries[c->count];
    strncpy(e->key, key, CONFIG_KEY_MAX - 1);
    e->key[CONFIG_KEY_MAX - 1] = '\0';
    strncpy(e->value, value, CONFIG_VALUE_MAX - 1);
    e->value[CONFIG_VALUE_MAX - 1] = '\0';
    c->count++;
}

int config_load(config *c, const char *path) {
    if (c == NULL || path == NULL) {
        return -1;
    }
    config_init(c);
    FILE *fp = fopen(path, "r");
    if (fp == NULL) {
        return -1;
    }
    char line[256];
    while (fgets(line, sizeof(line), fp) != NULL) {
        /* Hapus newline. */
        size_t len = strlen(line);
        while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) {
            line[--len] = '\0';
        }
        parse_line(line, c);
    }
    fclose(fp);
    return c->count;
}

const char *config_get(const config *c, const char *key) {
    if (c == NULL || key == NULL) {
        return NULL;
    }
    for (int i = 0; i < c->count; i++) {
        if (strcmp(c->entries[i].key, key) == 0) {
            return c->entries[i].value;
        }
    }
    return NULL;
}

int config_get_int(const config *c, const char *key, int default_value) {
    const char *v = config_get(c, key);
    if (v == NULL) {
        return default_value;
    }
    return (int)strtol(v, NULL, 10);
}
