import { Tty } from "../Tty.ts";

window.Terminal.registerCommand("cd", function (this: Tty, ...args) {
    let inputPath = args[0] || "~"; // Default to home if no args

    // 1. Expand the tilde and handle absolute vs relative
    let fullPath = inputPath.replace(/^~/, "/home/ubuntu");
    if (!fullPath.startsWith("/")) {
        fullPath = this.currentDir + "/" + fullPath;
    }

    // 2. Normalize the path (The "Magic" Step)
    // This removes '.' and resolves '..' correctly
    const segments = fullPath.split("/").filter((p) => p.length > 0 && p !== ".");
    const stack: string[] = [];

    for (const segment of segments) {
        if (segment === "..") {
            stack.pop(); // Go up one level
        } else {
            stack.push(segment);
        }
    }

    const target = "/" + stack.join("/");

    // 3. Validation
    try {
        // Assuming traverse throws if the path doesn't exist in your object
        this.traverse(target);
        this.currentDir = target || "/";
        return 0;
    } catch (e) {
        if (e.message === "Not directory") {
            this.currentDir = target.split("/").slice(0, -1).join("/") || "/";
            return 0;
        }

        return `cd: ${inputPath}: No such file or directory`;
    }
});
