import { error, warning } from "@/utils/formatter";
import { OutputFormatter } from "@/utils/output-formatter";
import type { OutputFormat } from "@/utils/cli-options";

export class CommandError extends Error {
  constructor(
    message: string,
    public readonly code: number = 1,
    public readonly showHelp: boolean = false
  ) {
    super(message);
    this.name = "CommandError";
  }
}

export class ValidationError extends CommandError {
  constructor(message: string) {
    super(message, 1, true);
    this.name = "ValidationError";
  }
}

export class GitError extends CommandError {
  constructor(message: string) {
    super(message, 1, false);
    this.name = "GitError";
  }
}

export class ProviderError extends CommandError {
  constructor(message: string) {
    super(message, 1, false);
    this.name = "ProviderError";
  }
}

/**
 * Handle errors consistently across commands
 */
export function handleError(
  err: unknown,
  outputFormat: OutputFormat = "text"
): never {
  const message = err instanceof Error ? err.message : String(err);
  const code = err instanceof CommandError ? err.code : 1;

  if (outputFormat === "json") {
    console.log(OutputFormatter.formatError(message, outputFormat));
  } else {
    error(message);
    if (err instanceof CommandError && err.showHelp) {
      console.log("\nRun 'agi --help' for usage information");
    }
  }

  process.exit(code);
}

/**
 * Handle warnings consistently across commands
 */
export function handleWarning(
  message: string,
  outputFormat: OutputFormat = "text"
): void {
  if (outputFormat === "json") {
    console.log(
      JSON.stringify({
        status: "warning",
        message,
        timestamp: new Date().toISOString(),
      })
    );
  } else {
    warning(message);
  }
}