// Show helpful information about a command.
//
// (Hopefully.)

import { commandPath } from "@/commands"
import type { CommandOutput } from "@/shared/types"
import { moduleExports, type ExportInfo } from "@/sniffer"
import commands from "./commands"

export default async function (cmd: string): Promise<CommandOutput> {
  if (!cmd) return "usage: help <command>"

  const path = commandPath(cmd)
  if (!path) return await commands(cmd)

  const signatures = await moduleExports(path)
  const signature = signatures.default

  const code = (await Bun.file(path).text()).split("\n")
  let docs = []

  docs.push(usage(cmd, signature), "")

  for (const line of code) {
    if (line.startsWith("///")) {
      docs.push("Runs in the browser.\n")
      continue
    } else if (line.startsWith("//")) {
      docs.push(line.slice(2).trim())
    } else if (line.trim()) {
      break
    }
  }

  return docs.join("\n")
}

function usage(cmd: string, signature?: ExportInfo) {
  let out: string[] = [`usage: ${cmd}`]

  if (signature?.kind === "function" && signature.signatures.length) {
    const params = signature.signatures[0]!.params
    for (const param of params) {
      let desc = param.default ? `[${param.name}=${param.default}]` : `<${param.name}>`
      desc +=
        out.push(desc)
    }
  }

  return out.join(" ")
}