import type { FileSystemNode } from "./types";
import { resolvePath } from "./fs";

export function getCompletions(
  input: string,
  currentPath: string,
  fileSystem: { [key: string]: FileSystemNode },
): { completion: string | null; replaceFrom: number } {
  const parts = input.trim().split(" ");
  const command = parts[0];
  const partialPath = parts[parts.length - 1] || "";

  // Only complete paths for these commands
  if (parts.length > 1 && ["ls", "cd", "cat", "open"].includes(command)) {
    // Path completion
    const isAbsolute = partialPath.startsWith("/");
    const pathToComplete = isAbsolute
      ? partialPath
      : resolvePath(currentPath, partialPath);

    // Find the directory to search in and the prefix to match
    let dirPath: string;
    let searchPrefix: string;

    if (pathToComplete.endsWith("/")) {
      // Path ends with slash - complete inside this directory
      dirPath = pathToComplete;
      searchPrefix = "";
    } else {
      // Base case - find directory and prefix
      const lastSlash = pathToComplete.lastIndexOf("/");
      if (lastSlash >= 0) {
        dirPath = pathToComplete.substring(0, lastSlash + 1);
        searchPrefix = pathToComplete.substring(lastSlash + 1);
      } else {
        dirPath = currentPath.endsWith("/") ? currentPath : currentPath + "/";
        searchPrefix = pathToComplete;
      }
    }

    // Calculate where to start replacement in the original input
    const spaceBeforeArg = input.lastIndexOf(" ");
    const replaceFrom = spaceBeforeArg >= 0 ? spaceBeforeArg + 1 : 0;

    // Navigate to the directory
    const dirParts = dirPath.split("/").filter((part: string) => part !== "");
    let current = fileSystem["/"];

    for (const part of dirParts) {
      if (
        current?.children &&
        current.children[part] &&
        current.children[part].type === "directory"
      ) {
        current = current.children[part];
      } else {
        return { completion: null, replaceFrom };
      }
    }

    if (!current?.children) {
      return { completion: null, replaceFrom };
    }

    // Get first matching item
    const match = Object.keys(current.children).find((name) =>
      name.startsWith(searchPrefix),
    );

    if (match) {
      const item = current.children[match];
      const completion = item.type === "directory" ? `${match}/` : match;
      return { completion, replaceFrom };
    }
  }

  return { completion: null, replaceFrom: input.length };
}

export function formatOutput(text: string): string {
  return text
    .replace(/\x1b\[34m/g, '<span class="text-primary">')
    .replace(/\x1b\[0m/g, "</span>");
}

export function saveCommandToHistory(
  command: string,
  persistentHistory: string[],
): string[] {
  if (command.trim()) {
    const updatedHistory = [...persistentHistory, command].slice(-100); // Keep last 100 commands
    localStorage.setItem("terminal-history", JSON.stringify(updatedHistory));
    return updatedHistory;
  }
  return persistentHistory;
}

export function loadCommandHistory(): string[] {
  const savedHistory = localStorage.getItem("terminal-history");
  if (savedHistory) {
    try {
      return JSON.parse(savedHistory);
    } catch (error) {
      console.error("Error loading command history:", error);
    }
  }
  return [];
}
