#include "dropfile.h"

int dropfile_detect(const char *explicit_path, char *found, size_t found_sz) {
    if (explicit_path && file_exists(explicit_path)) {
        safe_strcpy(found, explicit_path, found_sz);
        return 1;
    }
    const char *candidates[] = {"DOOR32.SYS", "door32.sys", "DOOR.SYS", "door.sys"};
    for (size_t i = 0; i < ARRAY_SIZE(candidates); i++) {
        if (file_exists(candidates[i])) {
            safe_strcpy(found, candidates[i], found_sz);
            return 1;
        }
    }
    return 0;
}

static int load_door32(const char *path, dropfile_info_t *out, bookmark_t *bm) {
    FILE *fp = fopen(path, "r");
    if (!fp) return -1;
    char lines[16][256];
    int count = 0;
    while (count < 16 && fgets(lines[count], sizeof(lines[count]), fp)) {
        trim(lines[count]);
        count++;
    }
    fclose(fp);
    if (count < 5) return -1;
    memset(out, 0, sizeof(*out));
    out->active = 1;
    out->node = atoi(lines[0]);
    safe_strcpy(out->alias, count > 5 ? lines[5] : "BBSUser", sizeof(out->alias));
    safe_strcpy(out->user_name, out->alias, sizeof(out->user_name));
    safe_strcpy(out->com_type, "DOOR32", sizeof(out->com_type));
    memset(bm, 0, sizeof(*bm));
    snprintf(bm->label, sizeof(bm->label), "BBS Door Session");
    snprintf(bm->server, sizeof(bm->server), "irc.libera.chat");
    bm->port = 6667;
    safe_strcpy(bm->nick, out->alias[0] ? out->alias : "BBSUser", sizeof(bm->nick));
    snprintf(bm->channel, sizeof(bm->channel), "##chat");
    bm->tls = 0;
    return 0;
}

static int load_door(const char *path, dropfile_info_t *out, bookmark_t *bm) {
    FILE *fp = fopen(path, "r");
    if (!fp) return -1;
    char lines[64][256];
    int count = 0;
    while (count < 64 && fgets(lines[count], sizeof(lines[count]), fp)) {
        trim(lines[count]);
        count++;
    }
    fclose(fp);
    if (count < 10) return -1;
    memset(out, 0, sizeof(*out));
    out->active = 1;
    safe_strcpy(out->com_type, "DOOR", sizeof(out->com_type));
    safe_strcpy(out->user_name, count > 9 ? lines[9] : "BBS User", sizeof(out->user_name));
    safe_strcpy(out->alias, count > 6 ? lines[6] : "BBSUser", sizeof(out->alias));
    memset(bm, 0, sizeof(*bm));
    snprintf(bm->label, sizeof(bm->label), "BBS Door Session");
    snprintf(bm->server, sizeof(bm->server), "irc.libera.chat");
    bm->port = 6667;
    safe_strcpy(bm->nick, out->alias[0] ? out->alias : "BBSUser", sizeof(bm->nick));
    snprintf(bm->channel, sizeof(bm->channel), "##chat");
    bm->tls = 0;
    return 0;
}

int dropfile_load(const char *path, dropfile_info_t *out, bookmark_t *bm) {
    const char *base = strrchr(path, '/');
#ifdef _WIN32
    const char *base2 = strrchr(path, '\\');
    if (!base || (base2 && base2 > base)) base = base2;
#endif
    base = base ? base + 1 : path;
    if (strcasecmp(base, "DOOR32.SYS") == 0) return load_door32(path, out, bm);
    return load_door(path, out, bm);
}
