/**
 * baseline command — manage historical baseline snapshots of evaluation scores.
 *
 * Wraps the core baseline functions from pipeline/baseline.ts behind a
 * Commander subcommand interface: `baseline save`, `baseline compare`,
 * `baseline history`. All three operate on the *caller's* `.ailf/results/`
 * tree (not the eval package's installed location); use `--baselines-dir`
 * or `AILF_BASELINES_DIR` to override (W0098).
 */
import { join, resolve } from "path";
import { Command } from "commander";
import { compareBaseline, listBaselines, saveBaseline, } from "../pipeline/baseline.js";
import { getCallerCwd } from "./shared/resolve-output-dir.js";
// CLI command name — kept as a constant to centralize the string literal.
// "baseline" here refers to score baseline snapshots, not the legacy eval mode.
const CMD_NAME = "baseline";
/**
 * Resolve the directory that holds baseline `*.json` snapshots.
 * Precedence: explicit flag > `AILF_BASELINES_DIR` env var > caller cwd default.
 */
function resolveBaselinesDir(flag) {
    if (flag)
        return resolve(getCallerCwd(), flag);
    if (process.env.AILF_BASELINES_DIR)
        return resolve(getCallerCwd(), process.env.AILF_BASELINES_DIR);
    return join(getCallerCwd(), ".ailf", "results", "baselines");
}
function resolveBaselineDirs(flag) {
    return {
        baselinesDir: resolveBaselinesDir(flag),
        scoreSummaryPath: join(getCallerCwd(), ".ailf", "results", "latest", "score-summary.json"),
    };
}
export function createBaselineCommand() {
    const cmd = new Command(CMD_NAME).description("Manage historical baseline snapshots of evaluation scores");
    // -----------------------------------------------------------------------
    // baseline save
    // -----------------------------------------------------------------------
    cmd
        .command("save")
        .description("Save current scores as a baseline snapshot")
        .option("-t, --tag <tag>", "Descriptive tag for the baseline")
        .option("--baselines-dir <path>", "Directory holding baseline snapshots (default: <cwd>/.ailf/results/baselines)")
        .action(async (opts) => {
        console.log("=== Saving baseline snapshot ===\n");
        const result = saveBaseline(resolveBaselineDirs(opts.baselinesDir), opts.tag);
        if (result.success) {
            console.log(`  ✅ ${result.message}`);
        }
        else {
            console.error(`  ❌ ${result.message}`);
            process.exit(1);
        }
    });
    // -----------------------------------------------------------------------
    // baseline compare
    // -----------------------------------------------------------------------
    cmd
        .command("compare")
        .description("Compare current scores against a saved baseline")
        .option("-f, --file <path>", "Specific baseline file to compare against")
        .option("--baselines-dir <path>", "Directory holding baseline snapshots (default: <cwd>/.ailf/results/baselines)")
        .action(async (opts) => {
        console.log("=== Baseline Comparison ===\n");
        const result = compareBaseline(resolveBaselineDirs(opts.baselinesDir), opts.file);
        if (!result.success) {
            console.error(`  ❌ ${result.message}`);
            process.exit(1);
        }
        console.log(`  ${result.message}\n`);
        // Score comparison table
        console.log("  " +
            "Feature Area".padEnd(18) +
            "Current".padEnd(10) +
            "Baseline".padEnd(10) +
            "Delta");
        console.log("  " + "-".repeat(50));
        for (const c of result.comparisons) {
            const deltaStr = c.delta > 0 ? `+${c.delta}` : c.delta === 0 ? "=" : String(c.delta);
            const icon = c.delta > 0 ? "📈" : c.delta < 0 ? "📉" : "➡️";
            console.log("  " +
                c.feature.padEnd(18) +
                String(c.current).padEnd(10) +
                String(c.baseline).padEnd(10) +
                `${icon} ${deltaStr}`);
        }
        // Cost comparison (only if cost data exists)
        const hasCostData = result.comparisons.some((c) => c.costCurrent !== undefined || c.costBaseline !== undefined);
        if (hasCostData) {
            console.log();
            console.log("  Cost Comparison:");
            console.log("  " +
                "Feature Area".padEnd(18) +
                "Current".padEnd(10) +
                "Baseline".padEnd(10) +
                "Delta");
            console.log("  " + "-".repeat(50));
            for (const c of result.comparisons) {
                if (c.costCurrent === undefined && c.costBaseline === undefined)
                    continue;
                const cur = `$${(c.costCurrent ?? 0).toFixed(4)}`;
                const base = `$${(c.costBaseline ?? 0).toFixed(4)}`;
                const delta = c.costDelta ?? 0;
                const deltaStr = delta > 0
                    ? `+$${delta.toFixed(4)}`
                    : delta < 0
                        ? `-$${Math.abs(delta).toFixed(4)}`
                        : "=";
                const icon = delta > 0 ? "📈" : delta < 0 ? "📉" : "➡️";
                console.log("  " +
                    c.feature.padEnd(18) +
                    cur.padEnd(10) +
                    base.padEnd(10) +
                    `${icon} ${deltaStr}`);
            }
        }
        console.log();
        const overallIcon = result.overallDelta > 0 ? "📈" : result.overallDelta < 0 ? "📉" : "➡️";
        const overallStr = result.overallDelta > 0
            ? `+${result.overallDelta}`
            : result.overallDelta === 0
                ? "="
                : String(result.overallDelta);
        console.log(`  Overall: ${overallIcon} ${overallStr} points`);
    });
    // -----------------------------------------------------------------------
    // baseline history
    // -----------------------------------------------------------------------
    cmd
        .command("history")
        .description("List all saved baselines")
        .option("--baselines-dir <path>", "Directory holding baseline snapshots (default: <cwd>/.ailf/results/baselines)")
        .action(async (opts) => {
        console.log("=== Baseline History ===\n");
        const baselines = listBaselines(resolveBaselinesDir(opts.baselinesDir));
        if (baselines.length === 0) {
            console.log("  No baselines saved yet.");
            return;
        }
        const hasCosts = baselines.some((b) => b.totalCost !== undefined || b.graderCost !== undefined);
        const costHeader = hasCosts ? "Cost".padEnd(10) : "";
        console.log("  " +
            "Date".padEnd(22) +
            "Avg".padEnd(6) +
            "Areas".padEnd(7) +
            costHeader +
            "Tag");
        console.log("  " + "-".repeat(hasCosts ? 60 : 50));
        for (const b of baselines) {
            const date = new Date(b.timestamp).toLocaleString();
            const combinedCost = (b.totalCost ?? 0) + (b.graderCost ?? 0);
            const costStr = hasCosts
                ? (combinedCost > 0 ? `$${combinedCost.toFixed(2)}` : "-").padEnd(10)
                : "";
            console.log("  " +
                date.padEnd(22) +
                String(b.avgScore).padEnd(6) +
                String(b.areaCount).padEnd(7) +
                costStr +
                (b.tag ?? ""));
        }
    });
    return cmd;
}
