import { Command } from "commander";

const OUTPUT_FORMATS = ['text', 'json', 'github'] as const;
export type OutputFormat = typeof OUTPUT_FORMATS[number];

/**
 * Common options shared across multiple commands
 */
export interface CommonOptions {
  provider?: string;
  model?: string;
  output?: OutputFormat;
  temperature?: number;
  maxTokens?: number;
  interactive?: boolean;
}

/**
 * Validate output format
 */
export function validateOutputFormat(format: string): format is OutputFormat {
  return OUTPUT_FORMATS.includes(format as OutputFormat);
}

/**
 * Add common AI provider options to a command
 */
export function addProviderOptions(command: Command): Command {
  return command
    .option("-p, --provider <provider>", "AI provider to use (gemini, anthropic, openai)")
    .option("-m, --model <model>", "Override default model for provider")
    .option("--temperature <value>", "Override temperature setting (0-1)", parseFloat)
    .option("--max-tokens <value>", "Override max tokens", parseInt);
}

/**
 * Add common output format options to a command
 */
export function addOutputOptions(command: Command): Command {
  return command
    .option("-o, --output <format>", "Output format: text, json, github (default: text)", (value) => {
      if (!validateOutputFormat(value)) {
        console.warn(`Warning: Invalid output format '${value}'. Falling back to 'text' format.`);
        return 'text' as OutputFormat;
      }
      return value as OutputFormat;
    })
    .option("--no-interactive", "Disable all interactive prompts (CI mode)");
}

/**
 * Add all common options to a command
 */
export function addCommonOptions(command: Command): Command {
  command = addProviderOptions(command);
  command = addOutputOptions(command);
  return command;
}

/**
 * Parse environment variables for CI/CD environments
 */
export function parseEnvironmentOptions(): Partial<CommonOptions> {
  const options: Partial<CommonOptions> = {};
  
  // Check if running in CI environment
  if (process.env.CI === 'true' || process.env.GITHUB_ACTIONS) {
    options.interactive = false;
  }
  
  // Allow env vars to override defaults
  if (process.env.AGI_PROVIDER) {
    options.provider = process.env.AGI_PROVIDER;
  }
  
  if (process.env.AGI_MODEL) {
    options.model = process.env.AGI_MODEL;
  }
  
  if (process.env.AGI_OUTPUT_FORMAT) {
    const format = process.env.AGI_OUTPUT_FORMAT;
    if (validateOutputFormat(format)) {
      options.output = format;
    }
  }
  
  return options;
}

/**
 * Merge options with environment defaults
 */
export function mergeWithEnvironment<T extends CommonOptions>(
  commandOptions: T
): T {
  const envOptions = parseEnvironmentOptions();
  return {
    ...envOptions,
    ...commandOptions,
    // Ensure interactive is properly set
    interactive: commandOptions.interactive ?? envOptions.interactive ?? true,
  };
}