#include "dshlib.h"
#include "rshlib.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/**
 * Parses a command string into a structured `command_list_t`
 */
int build_cmd_list(char *cmd, command_list_t *clist) {
    if (!cmd || !clist) return ERR_RDSH_CMD_PARSE;

    memset(clist, 0, sizeof(command_list_t));
    char *token = strtok(cmd, " ");
    if (!token) return ERR_RDSH_CMD_PARSE;

    clist->commands[0].argv[0] = strdup(token);
    int arg_count = 1;

    while ((token = strtok(NULL, " ")) != NULL) {
        clist->commands[0].argv[arg_count++] = strdup(token);
        if (arg_count >= MAX_ARGS) break;
    }

    clist->commands[0].argv[arg_count] = NULL;
    clist->command_count = 1;
    return OK;
}

/**
 * Identifies built-in commands.
 */
Built_In_Cmds rsh_match_command(const char *input) {
    if (strcmp(input, "exit") == 0) return BI_CMD_EXIT;
    if (strcmp(input, "stop-server") == 0) return BI_CMD_STOP_SVR;
    if (strcmp(input, "cd") == 0) return BI_CMD_CD;
    return BI_NOT_BI;
}

/**
 * Executes built-in commands (e.g., `cd`).
 */
int exec_builtin_command(Built_In_Cmds cmd_type, char *arg) {
    if (cmd_type == BI_CMD_CD) {
        if (chdir(arg) != 0) {
            perror("[ERROR] cd failed");
            return ERR_RDSH_CMD_EXEC;
        }
        return OK;
    }
    return ERR_RDSH_CMD_EXEC;
}

/**
 * Local shell execution loop.
 */
int exec_local_cmd_loop() {
    char command[RDSH_COMM_BUFF_SZ];

    while (1) {
        printf("dsh4> ");
        if (fgets(command, sizeof(command), stdin) == NULL) {
            printf("\n");
            break;
        }
        command[strcspn(command, "\n")] = '\0';

        if (strcmp(command, "exit") == 0) {
            printf("[DEBUG] Local shell exiting...\n");
            break;
        }

        system(command);
    }

    return OK;
}