import { dispatch } from "./src/dispatch.js";
import { CliError, errorMessage } from "./src/core/errors.js";
import { failure } from "./src/core/output.js";
import { buildRuntime, parseGlobalArgs } from "./src/core/runtime.js";

let currentServer: string | null = null;
let currentRequestId: string | null = null;

async function main(): Promise<number> {
  const { globals, rest } = parseGlobalArgs(process.argv.slice(2));
  if (isHelpRequest(rest)) {
    await dispatch(null, rest);
    return 0;
  }
  const ctx = await buildRuntime(globals);
  currentServer = ctx.server;
  currentRequestId = ctx.requestId;
  await dispatch(ctx, rest);
  return 0;
}

function isHelpRequest(argv: string[]): boolean {
  return argv.length === 0 || argv[0] === "help" || argv.includes("--help") || argv.at(-1) === "help";
}

try {
  process.exitCode = await main();
} catch (error) {
  if (error instanceof CliError) {
    failure({
      summary: error.summary,
      code: error.code,
      message: error.message,
      retryable: error.retryable,
      server: currentServer,
      requestId: currentRequestId,
      data: error.data,
      nextCommands: error.nextCommands,
    });
    process.exitCode = error.exitCode;
  } else {
    failure({ summary: "CLI 执行失败", code: "UNHANDLED_ERROR", message: errorMessage(error), retryable: false });
    process.exitCode = 1;
  }
}
