import subprocess
import os
from kytin.commands.base import Command


class CdCommand(Command):
    name = "cd"
    description = "Change directory"

    def run(self, cmd, context):
        parts = cmd.split()

        if len(parts) < 2:
            context.cwd = "/root"
            print("[+] Changed to home directory")
            return

        target = parts[1]

        # Absolute path
        if target.startswith("/"):
            new_path = target
        else:
            new_path = os.path.normpath(f"{context.cwd}/{target}")

        # Check inside container
        check_cmd = f"docker exec kytin_container bash -c 'test -d {new_path}'"
        result = subprocess.run(check_cmd, shell=True)

        if result.returncode == 0:
            context.cwd = new_path
            print(f"[+] Changed directory to {new_path}")
        else:
            print(f"[!] No such directory: {target}")