import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
import {
  TARGET_FILE_CANDIDATES,
  fileExists,
  findRepoRoot,
  runEvalCommand
} from "./chunk-LTALLYDW.js";
import {
  DEFAULT_EVAL_PATTERNS,
  deriveCategory,
  getAgentvHome,
  listTargetNames,
  loadConfig,
  readTargetDefinitions
} from "./chunk-URQXFJEB.js";
import "./chunk-C5GOHBQM.js";
import "./chunk-HQDCIXVH.js";
import "./chunk-BJV6MDBE.js";
import "./chunk-LRULMAAA.js";
import "./chunk-5H446C7X.js";

// src/commands/eval/interactive.ts
import path3 from "node:path";
import { checkbox, confirm, number, search, select } from "@inquirer/prompts";

// src/commands/eval/discover.ts
import path from "node:path";
import fg from "fast-glob";
async function discoverEvalFiles(cwd) {
  const repoRoot = await findRepoRoot(cwd);
  const config = await loadConfig(path.join(cwd, "_"), repoRoot);
  const patterns = config?.eval_patterns && config.eval_patterns.length > 0 ? config.eval_patterns : DEFAULT_EVAL_PATTERNS;
  const ignore = ["**/node_modules/**", "**/dist/**"];
  const matches = await fg(patterns, {
    cwd,
    absolute: true,
    onlyFiles: true,
    ignore,
    followSymbolicLinks: true,
    caseSensitiveMatch: false
  });
  const evalFiles = matches.map((absPath) => {
    const relativePath = path.relative(cwd, absPath);
    const category = deriveCategory(relativePath);
    return { path: absPath, relativePath, category };
  });
  evalFiles.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
  return evalFiles;
}
function getCategories(files) {
  const categories = /* @__PURE__ */ new Set();
  for (const file of files) {
    categories.add(file.category);
  }
  const sorted = Array.from(categories);
  sorted.sort();
  return sorted;
}
function filterByCategory(files, category) {
  return files.filter((f) => f.category === category);
}

// src/commands/eval/last-config.ts
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path2 from "node:path";
var AGENTV_DIR = getAgentvHome();
var LAST_CONFIG_PATH = path2.join(AGENTV_DIR, "last-config.json");
async function loadLastConfig() {
  try {
    const content = await readFile(LAST_CONFIG_PATH, "utf-8");
    return JSON.parse(content);
  } catch {
    return void 0;
  }
}
async function saveLastConfig(config) {
  await mkdir(AGENTV_DIR, { recursive: true });
  await writeFile(LAST_CONFIG_PATH, JSON.stringify(config, null, 2), "utf-8");
}

// src/commands/eval/interactive.ts
var ANSI_BOLD = "\x1B[1m";
var ANSI_DIM = "\x1B[2m";
var ANSI_CYAN = "\x1B[36m";
var ANSI_GREEN = "\x1B[32m";
var ANSI_RESET = "\x1B[0m";
async function launchInteractiveWizard() {
  const cwd = process.cwd();
  console.log(`
${ANSI_BOLD}${ANSI_CYAN}AgentV Interactive Mode${ANSI_RESET}
`);
  const lastConfig = await loadLastConfig();
  const action = await promptMainMenu(lastConfig);
  if (action === "exit") {
    return;
  }
  if (action === "rerun" && lastConfig) {
    console.log(`
${ANSI_DIM}Rerunning last configuration...${ANSI_RESET}
`);
    await executeConfig({
      evalPaths: lastConfig.evalPaths,
      target: lastConfig.target,
      workers: lastConfig.workers,
      dryRun: lastConfig.dryRun,
      cache: lastConfig.cache
    });
    return;
  }
  const config = await promptNewEvaluation(cwd);
  if (!config) {
    return;
  }
  const confirmed = await promptReviewAndConfirm(config, cwd);
  if (!confirmed) {
    return;
  }
  await saveLastConfig({
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    cwd,
    evalPaths: config.evalPaths,
    target: config.target,
    workers: config.workers,
    dryRun: config.dryRun,
    cache: config.cache
  });
  await executeConfig(config);
}
async function promptMainMenu(lastConfig) {
  const choices = [];
  if (lastConfig) {
    const evalCount = lastConfig.evalPaths.length;
    choices.push({
      name: "\u{1F504} Rerun last config",
      value: "rerun",
      description: `${evalCount} eval file(s), target: ${lastConfig.target}`
    });
  }
  choices.push({ name: "\u{1F680} Run new evaluation", value: "new" }, { name: "\u2715 Exit", value: "exit" });
  return select({
    message: "What would you like to do?",
    choices
  });
}
async function promptNewEvaluation(cwd) {
  console.log(`
${ANSI_DIM}Scanning for eval files...${ANSI_RESET}`);
  const allFiles = await discoverEvalFiles(cwd);
  if (allFiles.length === 0) {
    console.log(
      "\n\u26A0  No eval files found in the current directory.\n   Place .yaml or .jsonl eval files in your project, or use:\n   agentv eval <path-to-eval.yaml>\n"
    );
    return void 0;
  }
  console.log(`${ANSI_DIM}Found ${allFiles.length} eval file(s)${ANSI_RESET}
`);
  const selectedFiles = await promptEvalSelection(allFiles);
  if (selectedFiles.length === 0) {
    console.log("\nNo eval files selected.");
    return void 0;
  }
  const target = await promptTargetSelection(cwd, selectedFiles[0].path);
  const advanced = await promptAdvancedOptions();
  return {
    evalPaths: selectedFiles.map((f) => f.path),
    target,
    ...advanced
  };
}
async function promptEvalSelection(allFiles) {
  const categories = getCategories(allFiles);
  let filesToSelect;
  if (categories.length > 1) {
    const selectedCategory = await search({
      message: "Select a category (type to search)",
      source: async (term) => {
        const filtered = term ? categories.filter((c) => c.toLowerCase().includes(term.toLowerCase())) : categories;
        return [
          { name: "(all categories)", value: "__all__" },
          ...filtered.map((c) => {
            const count = filterByCategory(allFiles, c).length;
            return { name: `${c} (${count} file${count > 1 ? "s" : ""})`, value: c };
          })
        ];
      }
    });
    filesToSelect = selectedCategory === "__all__" ? allFiles : filterByCategory(allFiles, selectedCategory);
  } else {
    filesToSelect = allFiles;
  }
  return checkbox({
    message: "Select eval files to run (space to toggle, enter to confirm)",
    choices: filesToSelect.map((f) => ({
      name: f.relativePath,
      value: f,
      checked: filesToSelect.length <= 5
      // auto-select if few files
    })),
    required: true
  });
}
async function promptTargetSelection(cwd, firstEvalPath) {
  const repoRoot = await findRepoRoot(cwd);
  const targetsPath = await findTargetsFile(cwd, repoRoot, firstEvalPath);
  if (!targetsPath) {
    console.log(`${ANSI_DIM}No targets.yaml found. Using default target.${ANSI_RESET}`);
    return "default";
  }
  const definitions = await readTargetDefinitions(targetsPath);
  const targetNames = listTargetNames(definitions);
  if (targetNames.length === 0) {
    return "default";
  }
  if (targetNames.length === 1) {
    console.log(`${ANSI_DIM}Using target: ${targetNames[0]}${ANSI_RESET}`);
    return targetNames[0];
  }
  return search({
    message: "Select a target (type to search)",
    source: async (term) => {
      const filtered = term ? targetNames.filter((t) => t.toLowerCase().includes(term.toLowerCase())) : targetNames;
      return filtered.map((t) => {
        const def = definitions.find((d) => d.name === t);
        return {
          name: t,
          value: t,
          description: def ? `provider: ${def.provider}` : void 0
        };
      });
    }
  });
}
async function findTargetsFile(cwd, repoRoot, evalFilePath) {
  const dirsToSearch = [];
  if (evalFilePath) {
    const evalDir = path3.dirname(evalFilePath);
    if (!dirsToSearch.includes(evalDir)) {
      dirsToSearch.push(evalDir);
    }
  }
  if (!dirsToSearch.includes(cwd)) {
    dirsToSearch.push(cwd);
  }
  if (repoRoot !== cwd && !dirsToSearch.includes(repoRoot)) {
    dirsToSearch.push(repoRoot);
  }
  for (const dir of dirsToSearch) {
    for (const candidate of TARGET_FILE_CANDIDATES) {
      const fullPath = `${dir}/${candidate}`;
      if (await fileExists(fullPath)) {
        return fullPath;
      }
    }
  }
  return void 0;
}
async function promptAdvancedOptions() {
  const customize = await confirm({
    message: "Configure advanced options?",
    default: false
  });
  if (!customize) {
    return { workers: 3, dryRun: false, cache: false };
  }
  const workers = await number({
    message: "Number of parallel workers (1-50)",
    default: 3,
    min: 1,
    max: 50
  }) ?? 3;
  const dryRun = await confirm({
    message: "Enable dry-run mode (mock responses)?",
    default: false
  });
  const cache = await confirm({
    message: "Enable response cache?",
    default: false
  });
  return { workers, dryRun, cache };
}
async function promptReviewAndConfirm(config, cwd) {
  const evalDisplay = config.evalPaths.map((p) => {
    const rel = p.startsWith(cwd) ? p.slice(cwd.length + 1) : p;
    return `  ${rel}`;
  }).join("\n");
  console.log(`
${ANSI_BOLD}Review Configuration${ANSI_RESET}`);
  console.log(`${ANSI_DIM}${"\u2500".repeat(40)}${ANSI_RESET}`);
  console.log(`${ANSI_GREEN}Eval files:${ANSI_RESET}
${evalDisplay}`);
  console.log(`${ANSI_GREEN}Target:${ANSI_RESET}    ${config.target}`);
  console.log(`${ANSI_GREEN}Workers:${ANSI_RESET}   ${config.workers}`);
  console.log(`${ANSI_GREEN}Dry run:${ANSI_RESET}   ${config.dryRun ? "yes" : "no"}`);
  console.log(`${ANSI_GREEN}Cache:${ANSI_RESET}     ${config.cache ? "yes" : "no"}`);
  console.log(`${ANSI_DIM}${"\u2500".repeat(40)}${ANSI_RESET}`);
  return confirm({
    message: "Run evaluation with this configuration?",
    default: true
  });
}
async function executeConfig(config) {
  const rawOptions = {
    target: config.target,
    workers: config.workers,
    dryRun: config.dryRun,
    cache: config.cache,
    outputFormat: "jsonl",
    dryRunDelay: 0,
    dryRunDelayMin: 0,
    dryRunDelayMax: 0,
    agentTimeout: 120,
    maxRetries: 2,
    verbose: false,
    keepWorkspaces: false,
    cleanupWorkspaces: false,
    trace: false
  };
  const result = await runEvalCommand({
    testFiles: [...config.evalPaths],
    rawOptions
  });
  if (result && result.executionErrorCount > 0 && process.stdin.isTTY) {
    await promptRetryErrors(config, result.outputPath);
  }
}
async function promptRetryErrors(config, outputPath) {
  const shouldRetry = await confirm({
    message: `Retry ${ANSI_BOLD}execution errors${ANSI_RESET} from this run?`,
    default: true
  });
  if (!shouldRetry) {
    return;
  }
  console.log(`
${ANSI_DIM}Retrying execution errors...${ANSI_RESET}
`);
  const rawOptions = {
    target: config.target,
    workers: config.workers,
    dryRun: config.dryRun,
    cache: config.cache,
    outputFormat: "jsonl",
    retryErrors: outputPath,
    out: outputPath,
    dryRunDelay: 0,
    dryRunDelayMin: 0,
    dryRunDelayMax: 0,
    agentTimeout: 120,
    maxRetries: 2,
    verbose: false,
    keepWorkspaces: false,
    cleanupWorkspaces: false,
    trace: false
  };
  const retryResult = await runEvalCommand({
    testFiles: [...config.evalPaths],
    rawOptions
  });
  if (retryResult && retryResult.executionErrorCount > 0 && process.stdin.isTTY) {
    await promptRetryErrors(config, retryResult.outputPath);
  }
}
export {
  launchInteractiveWizard
};
//# sourceMappingURL=interactive-UZBC7V4B.js.map