import { Oneshot, OneshotOptions } from './oneshot';
import { processMeldFile } from './meld';
import { AnthropicProvider } from './providers/anthropic';
import { loadConfig } from './config';
import { writeFileSync, unlinkSync, existsSync } from 'fs';
import { execSync } from 'child_process';
import { ToolError } from './errors';

export interface OneshotcatOptions {
  inputFile: string;
  model?: string;
  system?: string;
  systemFile?: string;
}

export class Oneshotcat {
  private options: OneshotcatOptions;

  constructor(options: OneshotcatOptions) {
    this.options = options;
  }

  public async process(): Promise<Array<{ variation?: any, systemPrompt: string, response: string }>> {
    // Check if input file exists
    if (!existsSync(this.options.inputFile)) {
      throw new ToolError(`Input file not found: ${this.options.inputFile}`, 'FILE_NOT_FOUND');
    }

    // Process the prompt script
    const { content: processedContent, errors } = await processMeldFile({
      inputPath: this.options.inputFile,
      workspacePath: process.cwd()
    });

    // Create a temporary file for the processed content
    const tempFile = '.temp-oneshot-expanded.md';
    writeFileSync(tempFile, processedContent);

    // If there are errors, include them in the output
    if (errors.length > 0) {
      const errorContent = errors.map(error => `Error: ${error}`).join('\n');
      writeFileSync(tempFile, processedContent + '\n\n' + errorContent);
    }

    // Load config and create provider
    const config = loadConfig();
    const provider = new AnthropicProvider(config.anthropicApiKey || '');

    // Then send to AI
    const oneshot = new Oneshot({
      model: this.options.model || 'claude-3',
      promptFile: tempFile,
      system: this.options.system,
      systemFile: this.options.systemFile
    }, provider);

    const responses = await oneshot.process();
    
    // Clean up temp file
    unlinkSync(tempFile);
    
    // Format response to match expected structure
    return responses.map(({ variation, systemPrompt, response }) => ({
      variation,
      systemPrompt,
      response
    }));
  }
} 