/**
 * Centralized user-facing error messages.
 *
 * Maps internal error conditions to actionable, user-friendly messages
 * that tell users exactly what to do to resolve the issue.
 * Internal server-console log messages remain unchanged.
 */

const IS_WINDOWS = process.platform === "win32";

/** Platform-appropriate command separator for multi-line instructions. */
const installSuffix = IS_WINDOWS
  ? "Then restart Zencode."
  : "Then restart Zencode.";

/**
 * Returns an actionable error message for a missing CLI binary.
 */
export function binaryNotFoundMessage(binary: string): string {
  switch (binary) {
    case "claude":
      return [
        `Claude Code CLI is not installed or not found in your PATH.`,
        ``,
        `To install it, run:`,
        `  npm install -g @anthropic-ai/claude-code`,
        ``,
        `${installSuffix}`,
        `If already installed, ensure it is on your PATH by running: claude --version`,
      ].join("\n");

    case "codex":
      return [
        `Codex CLI is not installed or not found in your PATH.`,
        ``,
        `To install it, run:`,
        `  npm install -g @openai/codex`,
        ``,
        `${installSuffix}`,
        `If already installed, ensure it is on your PATH by running: codex --version`,
      ].join("\n");

    default:
      return [
        `"${binary}" command not found.`,
        ``,
        `Make sure it is installed and accessible in your PATH.`,
        `Try running "${binary} --version" in your terminal to verify.`,
      ].join("\n");
  }
}

/**
 * Returns an actionable message for a CLI process that exited immediately.
 */
export function cliExitedImmediatelyMessage(binary: string, exitCode: number | null): string {
  const codeStr = exitCode != null ? ` (exit code ${exitCode})` : "";
  return [
    `${binary === "codex" ? "Codex" : "Claude Code"} CLI exited immediately${codeStr}.`,
    ``,
    `This usually means:`,
    `• The CLI version is incompatible — try updating: npm install -g ${binary === "codex" ? "@openai/codex" : "@anthropic-ai/claude-code"}@latest`,
    `• An API key is missing or invalid — check your ${binary === "codex" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY"} environment variable`,
    `• The CLI crashed on startup — try running "${binary} --version" in your terminal`,
  ].join("\n");
}

/**
 * Returns an actionable message for container-related binary not found errors.
 */
export function containerBinaryNotFoundMessage(binary: string, containerLabel: string): string {
  return [
    `"${binary}" command not found inside container "${containerLabel}".`,
    ``,
    `The container image may need to be rebuilt with the CLI installed.`,
    `Ensure the Dockerfile includes: npm install -g ${binary === "codex" ? "@openai/codex" : "@anthropic-ai/claude-code"}`,
  ].join("\n");
}

/**
 * Returns an actionable message for container state issues.
 */
export function containerStateMessage(containerLabel: string, state: "missing" | "stopped"): string {
  if (state === "missing") {
    return `Container "${containerLabel}" was removed externally. Please create a new session.`;
  }
  return `Container "${containerLabel}" is stopped and could not be restarted. Try creating a new session.`;
}

/**
 * Returns an actionable message for WebSocket / connection errors.
 */
export function connectionErrorMessage(context: string): string {
  switch (context) {
    case "ws_close":
      return "Connection to the server was lost. Zencode will attempt to reconnect automatically.";
    case "ws_error":
      return "WebSocket connection error. Check that the server is still running.";
    case "server_unreachable":
      return "Unable to reach the server. Is Zencode server still running?";
    default:
      return `Connection error: ${context}`;
  }
}

/**
 * Returns an actionable message for session creation failures.
 */
export function sessionCreationErrorMessage(rawError: string): string {
  // Check for common error patterns and provide guidance
  if (/command not found|not found in PATH|ENOENT/i.test(rawError)) {
    // Detect which binary from the message
    if (/codex/i.test(rawError)) {
      return binaryNotFoundMessage("codex");
    }
    return binaryNotFoundMessage("claude");
  }

  if (/ANTHROPIC_API_KEY|api.key|authentication.*failed/i.test(rawError)) {
    return [
      `Authentication failed with the Anthropic API.`,
      ``,
      `Make sure your ANTHROPIC_API_KEY is set correctly.`,
      `You can set it by running: claude login`,
    ].join("\n");
  }

  if (/OPENAI_API_KEY/i.test(rawError)) {
    return [
      `Authentication failed with the OpenAI API.`,
      ``,
      `Make sure your OPENAI_API_KEY environment variable is set.`,
      `Run: codex auth`,
    ].join("\n");
  }

  if (/docker|container/i.test(rawError) && /not found|not installed|ENOENT/i.test(rawError)) {
    return [
      `Docker is not installed or not running.`,
      ``,
      `Container-based sessions require Docker Desktop or Docker Engine.`,
      `Install Docker from: https://docs.docker.com/get-docker/`,
    ].join("\n");
  }

  if (/ECONNREFUSED|ETIMEDOUT|network/i.test(rawError)) {
    return [
      `Network connection failed.`,
      ``,
      rawError,
      ``,
      `Check your network connection and try again.`,
    ].join("\n");
  }

  // Return the original message if no pattern matches — it may already be descriptive
  return rawError;
}
