/**
 * Interactive mode — guided wizard for the evaluation pipeline.
 *
 * When `ailf` is run with no arguments (or `ailf interactive`), this module
 * prompts the user through mode selection, area scoping, debug options,
 * and common flags — then builds and executes the equivalent `ailf run`
 * command.
 *
 * Uses @inquirer/prompts for a clean, modern terminal UI.
 */
import { Command } from "commander";
import { LiteracyVariant } from "../pipeline/normalize-mode.js";
// CLI command name for the baseline snapshot management subcommand.
// Defined as a constant to avoid scattering the literal string across routing code.
const BASELINE_CMD = "baseline";
export function createInteractiveCommand() {
    return new Command("interactive")
        .description("Guided wizard for common evaluation workflows")
        .action(async () => {
        const result = await runInteractiveWizard();
        if (!result)
            return;
        console.log();
        console.log(`  ▸ ailf ${result.command} ${result.args.join(" ")}`);
        console.log();
        // Dynamically import the CLI entry point's program and re-parse
        // with the synthesized argv. This avoids shelling out and keeps
        // everything in-process.
        const { execSync } = await import("child_process");
        const fullCommand = `tsx src/cli.ts ${result.command} ${result.args.join(" ")}`;
        try {
            execSync(fullCommand, { stdio: "inherit" });
        }
        catch (err) {
            const code = err !== null && typeof err === "object" && "status" in err
                ? err.status
                : 1;
            process.exit(code);
        }
    });
}
// ---------------------------------------------------------------------------
// Wizard steps
// ---------------------------------------------------------------------------
async function runInteractiveWizard() {
    const { confirm, input, select } = await import("@inquirer/prompts");
    console.log();
    console.log("  🧙 AI Literacy Framework — Interactive Mode");
    console.log("  ────────────────────────────────────────────");
    console.log();
    // Step 1: Choose workflow
    const workflow = await select({
        choices: [
            {
                description: "Full evaluation run (fetch → eval → score → report)",
                name: "Run evaluation",
                value: "run",
            },
            {
                description: "Compare current scores against a saved baseline",
                name: "Compare scores",
                value: "compare",
            },
            {
                description: "Check YAML files, mappings, and reference solutions",
                name: "Validate config",
                value: "validate",
            },
            {
                description: "Save, compare, or list historical score snapshots",
                name: "Manage baselines",
                value: BASELINE_CMD,
            },
            {
                description: "Weekly evaluation trends and area summaries",
                name: "Weekly digest",
                value: "weekly-digest",
            },
            {
                description: "Measure grader reliability and discrimination power",
                name: "Grader tools",
                value: "grader",
            },
        ],
        message: "What would you like to do?",
    });
    if (workflow === "compare") {
        return { args: [], command: "compare" };
    }
    if (workflow === "validate") {
        return { args: [], command: "validate" };
    }
    if (workflow === "weekly-digest") {
        const dryRun = await confirm({
            default: true,
            message: "Dry run? (preview to stdout, don't send to Slack)",
        });
        return { args: dryRun ? ["--dry-run"] : [], command: "weekly-digest" };
    }
    if (workflow === BASELINE_CMD) {
        const subcommand = await select({
            choices: [
                { name: "Save current scores", value: "save" },
                { name: "Compare against latest", value: "compare" },
                { name: "List saved baselines", value: "history" },
            ],
            message: "Baseline operation:",
        });
        return { args: [subcommand], command: BASELINE_CMD };
    }
    if (workflow === "grader") {
        const subcommand = await select({
            choices: [
                {
                    description: "Measure grading variance across replications",
                    name: "Consistency analysis",
                    value: "consistency",
                },
                {
                    description: "Test grader discrimination across quality levels",
                    name: "Sensitivity test",
                    value: "sensitivity",
                },
                {
                    description: "Compare two grader models head-to-head",
                    name: "Compare graders",
                    value: "compare",
                },
                {
                    description: "Validate against human reference grades",
                    name: "Validate grader",
                    value: "validate",
                },
            ],
            message: "Grader tool:",
        });
        return { args: [subcommand], command: "grader" };
    }
    // --- Pipeline-specific wizard continues below ---
    const args = [];
    // Step 2: Evaluation mode
    const mode = await select({
        choices: [
            {
                description: "Evaluate with pre-fetched documentation context",
                name: "Baseline (with docs vs without docs)",
                value: LiteracyVariant.STANDARD,
            },
            {
                description: "Baseline + record HTTP request patterns",
                name: "Observed (instrumented)",
                value: LiteracyVariant.OBSERVED,
            },
            {
                description: "Agent searches for docs itself via web tools",
                name: "Agentic (agent-driven retrieval)",
                value: LiteracyVariant.AGENTIC,
            },
        ],
        message: "Evaluation mode:",
    });
    if (mode !== LiteracyVariant.STANDARD) {
        args.push("--mode", mode);
    }
    // Step 3: Area scoping
    const scopeByArea = await confirm({
        default: false,
        message: "Scope to specific feature areas?",
    });
    if (scopeByArea) {
        const areas = await input({
            message: "Feature areas (comma-separated, e.g. groq,frameworks):",
        });
        if (areas.trim()) {
            args.push("--area", areas.trim());
        }
    }
    // Step 4: Debug mode
    const debug = await confirm({
        default: false,
        message: "Enable debug mode? (run a subset of tests for fast feedback)",
    });
    if (debug) {
        args.push("--debug");
        const debugStyle = await select({
            choices: [
                { name: "First 2 tests (default)", value: "default" },
                { name: "First N tests", value: "first-n" },
                { name: "Random sample", value: "sample" },
                { name: "Filter by pattern", value: "pattern" },
            ],
            message: "Debug scope:",
        });
        if (debugStyle === "first-n") {
            const n = await input({ default: "5", message: "Number of tests:" });
            args.push("--filter-first-n", n);
        }
        else if (debugStyle === "sample") {
            const n = await input({
                default: "3",
                message: "Sample size:",
            });
            args.push("--filter-sample", n);
        }
        else if (debugStyle === "pattern") {
            const pattern = await input({
                message: "Description regex (e.g. Blog, webhook):",
            });
            if (pattern.trim()) {
                args.push("--filter-pattern", pattern.trim());
            }
        }
    }
    // Step 5: Common pipeline options
    const dryRun = await confirm({
        default: false,
        message: "Dry run? (validate config only, no API calls)",
    });
    if (dryRun) {
        args.push("--dry-run");
    }
    if (!dryRun) {
        const compareAfter = await confirm({
            default: false,
            message: "Compare against baseline after evaluation?",
        });
        if (compareAfter) {
            args.push("--compare");
        }
    }
    // Step 6: Preview execution plan before running
    if (!dryRun) {
        const preview = await confirm({
            default: true,
            message: "Preview execution plan before running? (--explain --yes)",
        });
        if (preview) {
            args.push("--explain", "--yes");
        }
    }
    return { args, command: "run" };
}
