////
// The shell runs on the server and processes input, returning output.

import type { InputMessage } from "../shared/types"
import { addInput, setStatus, addOutput } from "./scrollback"
import { send } from "./websocket"
import { randomId, importUrl } from "../shared/utils"
import { addToHistory } from "./history"
import { commands } from "./commands"

export async function runCommand(input: string, showInput = true) {
    if (!input.trim()) return

    if (input.includes(";")) {
        input.split(";").forEach(async cmd => await runCommand(cmd.trim()))
        return
    }

    const id = randomId()

    addToHistory(input)
    if (showInput)
        addInput(id, input)

    const [cmd = "", ...args] = input.split(" ")

    if (commands[cmd]?.type === "browser") {
        const mod = await importUrl(`/source/${cmd}`)
        if (!mod.default) {
            addOutput(id, `no default export in ${cmd}`)
            setStatus(id, "error")
            return
        }
        const result = mod.default(...args)
        if (result) addOutput(id, result)
        setStatus(id, "ok")
    } else {
        send({ id, type: "input", data: input } as InputMessage)
    }
}

