import { SimpleRalphPlugin } from "../simple-ralph-plugin.js";
import * as fs from "fs/promises";
import * as path from "path";
class CodeGenerator {
  ralphPlugin;
  constructor(ralphPlugin) {
    this.ralphPlugin = ralphPlugin;
  }
  /**
   * Generate code iteratively until it works
   */
  async generateCode(request) {
    const task = {
      id: `codegen-${Date.now()}`,
      description: `Generate ${request.language} code: ${request.description}`,
      acceptanceCriteria: this.buildCriteria(request),
      maxIterations: 5
    };
    await this.prepareOutputDirectory(request.outputPath);
    const result = await this.ralphPlugin.runTask(task);
    return {
      mainFile: path.join(request.outputPath, this.getMainFileName(request)),
      testFile: request.includeTests ? path.join(request.outputPath, this.getTestFileName(request)) : void 0,
      dependencies: await this.extractDependencies(request.outputPath),
      success: result.success,
      iterations: result.iterations
    };
  }
  /**
   * Build acceptance criteria based on request
   */
  buildCriteria(request) {
    const criteria = [];
    criteria.push("Code compiles/runs without errors");
    criteria.push("Code implements requested functionality");
    switch (request.language) {
      case "typescript":
        criteria.push("TypeScript compiles without errors");
        criteria.push("No any types unless necessary");
        break;
      case "javascript":
        criteria.push("Passes ESLint checks");
        break;
      case "python":
        criteria.push("Passes flake8 checks");
        criteria.push("Type hints included");
        break;
    }
    if (request.includeTests) {
      criteria.push("Tests pass");
      criteria.push("Test coverage > 80%");
    }
    if (request.requirements) {
      criteria.push(...request.requirements);
    }
    return criteria;
  }
  /**
   * Prepare output directory
   */
  async prepareOutputDirectory(outputPath) {
    await fs.mkdir(outputPath, { recursive: true });
  }
  /**
   * Get main file name based on language
   */
  getMainFileName(request) {
    const baseName = "index";
    switch (request.language) {
      case "typescript":
        return `${baseName}.ts`;
      case "javascript":
        return `${baseName}.js`;
      case "python":
        return `${baseName}.py`;
      default:
        return baseName;
    }
  }
  /**
   * Get test file name based on language
   */
  getTestFileName(request) {
    const baseName = "index";
    switch (request.language) {
      case "typescript":
        return `${baseName}.test.ts`;
      case "javascript":
        return `${baseName}.test.js`;
      case "python":
        return `test_${baseName}.py`;
      default:
        return `${baseName}.test`;
    }
  }
  /**
   * Extract dependencies from generated code
   */
  async extractDependencies(outputPath) {
    const dependencies = [];
    try {
      const packageJsonPath = path.join(outputPath, "package.json");
      try {
        const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
        dependencies.push(...Object.keys(packageJson.dependencies || {}));
        dependencies.push(...Object.keys(packageJson.devDependencies || {}));
      } catch {
      }
      const requirementsPath = path.join(outputPath, "requirements.txt");
      try {
        const requirements = await fs.readFile(requirementsPath, "utf-8");
        dependencies.push(...requirements.split("\n").filter((l) => l.trim()));
      } catch {
      }
    } catch (error) {
      console.error("Error extracting dependencies:", error);
    }
    return [...new Set(dependencies)];
  }
}
async function generateAPIEndpoint() {
  const ralphPlugin = new SimpleRalphPlugin();
  await ralphPlugin.initialize({
    eventBus: {},
    config: { name: "simple-ralph", version: "2.0.0", enabled: true },
    dataDir: ".ralph",
    getRepository: () => null,
    registerRepository: () => {
    }
  });
  const generator = new CodeGenerator(ralphPlugin);
  const result = await generator.generateCode({
    description: "REST API endpoint for user management with CRUD operations",
    language: "typescript",
    outputPath: "./generated/api",
    includeTests: true,
    testFramework: "jest",
    requirements: [
      "Use Express.js",
      "Include validation",
      "Add error handling",
      "Support pagination"
    ]
  });
  console.log("Code generation result:", result);
}
export {
  CodeGenerator,
  generateAPIEndpoint
};
//# sourceMappingURL=code-generator.js.map
