import type { QueueTaskItem, QueueTaskItemStatus } from "@codeflash/types";

export function canRetryTaskInQueue(task: QueueTaskItem): boolean {
  return (
    task.status === "skipped" ||
    task.status === "failed" ||
    task.status === "canceled" ||
    task.status === "rejected"
  );
}

export function canDeleteTaskInQueue(
  task: QueueTaskItem,
  deleteSuccessfulTasksAlso: boolean = false,
): boolean {
  if (task.status === "completed") {
    return deleteSuccessfulTasksAlso;
  }
  return !isTaskRunning(task);
}

export function isTaskRunning(task: QueueTaskItem): boolean {
  return task.status === "optimizing" || task.status === "initializing";
}

export function formatDuration(ns: number): string {
  if (ns < 1_000) {
    return `${ns} ns`;
  } else if (ns < 1_000_000) {
    return `${(ns / 1e3).toFixed(2)} µs`;
  } else if (ns < 1_000_000_000) {
    return `${(ns / 1e6).toFixed(2)} ms`;
  } else {
    return `${(ns / 1e9).toFixed(2)} s`;
  }
}

export function canTaskPersistInTheDisk(task: QueueTaskItem): boolean {
  return (
    ["completed", "canceled", "rejected"] as QueueTaskItemStatus[]
  ).includes(task.status);
}

export const getFileNameFromPath = (path: string) => {
  // Handle both Windows (\) and Unix (/) path separators
  const normalizedPath = path.replace(/\\/g, "/");
  const parts = normalizedPath.split("/");
  return parts[parts.length - 1];
};

export const isOutsideModuleRoot = (
  moduleRoot: string,
  filePath: string,
): boolean => {
  const trimmedModuleRoot = moduleRoot.trim();
  if (!trimmedModuleRoot) {
    return false;
  }

  const rootUrl = new URL(`file://${trimmedModuleRoot.replace(/\\/g, "/")}/`);
  const fileUrl = new URL(`file://${filePath.replace(/\\/g, "/")}`);

  const rootPath = rootUrl.pathname;
  const targetPath = fileUrl.pathname;

  return !targetPath.startsWith(rootPath);
};
