import { ConfigManager } from "@/config/manager";
import { ProviderRegistry } from "@/utils/provider-registry";
import { OutputFormatter } from "@/utils/output-formatter";
import { error } from "@/utils/formatter";
import type { CommonOptions } from "./cli-options";
import type { GenerateOptions } from "@/providers/base";

/**
 * Base class for command execution with common functionality
 */
export abstract class CommandBase {
  protected options: CommonOptions;
  protected outputFormat: string;
  
  constructor(options: CommonOptions) {
    this.options = options;
    this.outputFormat = options.output || 'text';
  }
  
  /**
   * Get the provider instance with proper configuration
   */
  protected async getProvider() {
    const providerName = this.options.provider || (await ConfigManager.get("defaultProvider"));
    return ProviderRegistry.getProvider(providerName);
  }
  
  /**
   * Get generation options from command options
   */
  protected getGenerateOptions(): GenerateOptions {
    return {
      temperature: this.options.temperature,
      maxTokens: this.options.maxTokens,
      model: this.options.model,
    };
  }
  
  /**
   * Handle errors with proper formatting
   */
  protected handleError(message: string, exitCode: number = 1): never {
    if (this.outputFormat === 'json') {
      console.log(OutputFormatter.formatError(message, 'json'));
    } else {
      error(message);
    }
    process.exit(exitCode);
  }
  
  /**
   * Check if running in interactive mode
   */
  protected isInteractive(): boolean {
    return this.options.interactive !== false && !process.env.CI;
  }
}