#!/usr/bin/env npx tsx
import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import * as fs from "fs/promises";
import * as path from "path";
import { existsSync } from "fs";
const RALPH_DIR = ".ralph";
const MAX_TEST_ITERATIONS = 10;
async function ensureDirectory(dir) {
  if (!existsSync(dir)) {
    await fs.mkdir(dir, { recursive: true });
  }
}
async function saveLoopState(state) {
  await fs.writeFile(
    path.join(RALPH_DIR, "state.json"),
    JSON.stringify(state, null, 2)
  );
  await fs.writeFile(
    path.join(RALPH_DIR, "iteration.txt"),
    state.iteration.toString()
  );
  console.log(`\u2705 Saved state for iteration ${state.iteration}`);
}
async function simulateIteration(iterationNum) {
  const historyDir = path.join(
    RALPH_DIR,
    "history",
    `iteration-${iterationNum.toString().padStart(3, "0")}`
  );
  await ensureDirectory(historyDir);
  const artifacts = {
    analysis: {
      filesCount: Math.floor(Math.random() * 10) + 1,
      testsPass: Math.floor(Math.random() * 20),
      testsFail: Math.floor(Math.random() * 5),
      lastChange: `Iteration ${iterationNum} changes`
    },
    plan: {
      summary: `Work for iteration ${iterationNum}`,
      steps: [
        `Task ${iterationNum}-1`,
        `Task ${iterationNum}-2`,
        `Task ${iterationNum}-3`
      ],
      priority: "high"
    },
    changes: [
      {
        step: `Task ${iterationNum}-1`,
        timestamp: Date.now(),
        result: "completed"
      }
    ],
    validation: {
      testsPass: true,
      lintClean: true,
      errors: []
    }
  };
  await fs.writeFile(
    path.join(historyDir, "artifacts.json"),
    JSON.stringify(artifacts, null, 2)
  );
  console.log(`\u{1F4DD} Created artifacts for iteration ${iterationNum}`);
}
async function runIterationTest() {
  console.log("\u{1F3AD} Starting Ralph iteration test...");
  console.log(`\u{1F3AF} Goal: Test ${MAX_TEST_ITERATIONS} iterations
`);
  await ensureDirectory(RALPH_DIR);
  await ensureDirectory(path.join(RALPH_DIR, "history"));
  const initialState = {
    task: "Test multiple iterations beyond 5",
    iteration: 0,
    status: "initialized",
    startTime: Date.now()
  };
  await saveLoopState(initialState);
  for (let i = 0; i < MAX_TEST_ITERATIONS; i++) {
    console.log(`
--- Iteration ${i} ---`);
    await simulateIteration(i);
    const state = {
      task: "Test multiple iterations beyond 5",
      iteration: i + 1,
      status: "running",
      startTime: initialState.startTime
    };
    await saveLoopState(state);
    if (i === 5) {
      console.log("\n\u{1F389} Successfully passed iteration 5!");
    }
    await new Promise((resolve) => setTimeout(resolve, 100));
  }
  console.log("\n\u2705 Test completed successfully!");
  console.log(`\u{1F4CA} Final iteration count: ${MAX_TEST_ITERATIONS}`);
  const finalIteration = await fs.readFile(
    path.join(RALPH_DIR, "iteration.txt"),
    "utf8"
  );
  const finalState = JSON.parse(
    await fs.readFile(path.join(RALPH_DIR, "state.json"), "utf8")
  );
  console.log(`
\u{1F4CB} Final verification:`);
  console.log(`   iteration.txt: ${finalIteration}`);
  console.log(`   state.json iteration: ${finalState.iteration}`);
  if (parseInt(finalIteration) === MAX_TEST_ITERATIONS) {
    console.log("\n\u{1F38A} SUCCESS: Ralph loop can iterate beyond 5 iterations!");
  } else {
    console.error("\n\u274C FAILURE: Iteration count mismatch");
  }
}
runIterationTest().catch((error) => {
  console.error("\u274C Test failed:", error);
  process.exit(1);
});
//# sourceMappingURL=test-ralph-iterations.js.map
