import { readConfig } from "./src/config";
import { isHelpToken, sshHelp } from "./src/help";
import { emitError, emitJson } from "./src/output";
import { extractRemoteCliOptions } from "./src/remote-options";
import { runRemoteSshCli } from "./src/remote-ssh";
import { runSsh } from "./src/ssh";

const remoteOptions = extractRemoteCliOptions(process.argv.slice(2));
const args = normalizeSshCommandArgs(remoteOptions.args);
const commandName = displayCommandName(args);

function normalizeSshCommandArgs(rawArgs: string[]): string[] {
  if (rawArgs[0] === "ssh") return rawArgs;
  return ["ssh", ...rawArgs];
}

function displayCommandName(normalizedArgs: string[]): string {
  const rawEntrypoint = process.env.UNIDESK_SSH_ENTRYPOINT?.trim();
  const entrypoint = rawEntrypoint === "trans" || rawEntrypoint === "tran" || rawEntrypoint === "ssh" ? rawEntrypoint : "ssh";
  const displayArgs = normalizedArgs[0] === "ssh" ? normalizedArgs.slice(1) : normalizedArgs;
  return [entrypoint, ...displayArgs].join(" ") || entrypoint;
}

function isGhContentRouteTarget(target: string | undefined): boolean {
  return typeof target === "string" && target.startsWith("gh:");
}

async function main(): Promise<void> {
  const [top, sub, third] = args;
  if (top !== "ssh") throw new Error(`ssh-cli supports only the ssh command, got: ${top || "<empty>"}`);

  if (sub === undefined || isHelpToken(sub) || (isHelpToken(third) && args.length === 3)) {
    emitJson(commandName, sshHelp());
    return;
  }

  if (remoteOptions.host !== null) {
    process.exitCode = await runRemoteSshCli({ ...remoteOptions, args }, readConfig());
    return;
  }

  if (isGhContentRouteTarget(sub)) {
    const { runGhContentRoute } = await import("./src/gh-route");
    process.exitCode = await runGhContentRoute(sub, args.slice(2));
    return;
  }

  process.exitCode = await runSsh(readConfig(), sub, args.slice(2));
}

main().catch((error) => {
  emitError(commandName, error);
  process.exitCode = 1;
});
