#include "utils.h"

void format_path(char *dest, char *src, int dest_len) {
  if (src == NULL || strcmp(src, "/") == 0 || strlen(src) == 0) {
    strcpy(dest, "/");
  } else if (src[0] == '/') {
    strncpy(dest, src, 1023);
  } else {
    char *current_pwd = get_env_value("PWD");
    snprintf(dest, dest_len, "%s/%s",
             strcmp(current_pwd, "/") == 0 ? "" : current_pwd, src);
  }
}

int get_name_and_parent_path_by_absolute_path(char* path, char** parent_path, char** name) {
      if (path == NULL || strlen(path) == 0) {
        return -1; 
    }

    size_t len = strlen(path);
    if (len > 1 && path[len - 1] == '/') {
        path[len - 1] = '\0';
    }

    char *last_occ = strrchr(path, '/');

    if (last_occ == NULL) {
        *parent_path = strdup(get_env_value("PWD"));
        *name = strdup(path);
    } else {
        *name = strdup(last_occ + 1);

        if (last_occ == path) {
            *parent_path = strdup("/");
        } else {
            *last_occ = '\0';
            *parent_path = strdup(path);
            *last_occ = '/';
        }
    }
  return 0;
}

int get_dirname_and_parent_path_by_absolute_path(char* dirpath, char** parent_path, char** dirname) {
    if (dirpath == NULL || strlen(dirpath) == 0) {
        return -1; 
    }

    size_t len = strlen(dirpath);
    if (len > 1 && dirpath[len - 1] == '/') {
        dirpath[len - 1] = '\0';
    }

    char *last_occ = strrchr(dirpath, '/');

    if (last_occ == NULL) {
        *parent_path = strdup(get_env_value("PWD")); 
        *dirname = strdup(dirpath);
    } else {
        
        *dirname = strdup(last_occ + 1);

        if (last_occ == dirpath) {
            *parent_path = strdup("/");
        } else {
            *last_occ = '\0';
            *parent_path = strdup(dirpath);
            *last_occ = '/';
        }
    }
    
    return 0;
}

void canonicalize_path(char *path) {
  char *tokens[100];
  int depth = 0;

  char *tmp = strdup(path);
  char *token = strtok(tmp, "/");

  while (token != NULL) {
    if (strcmp(token, "..") == 0) {
      if (depth > 0)
        depth--;
    } else if (strcmp(token, ".") != 0 && strlen(token) > 0) {
      tokens[depth++] = token;
    }
    token = strtok(NULL, "/");
  }

  strcpy(path, "/");
  for (int i = 0; i < depth; i++) {
    strcat(path, tokens[i]);
    if (i < depth - 1)
      strcat(path, "/");
  }

  free(tmp);
}