/**
 * discovery-report command — generates an agent discoverability report
 * from agentic mode retrieval metrics.
 *
 * Reads score-summary.json and produces a markdown report showing
 * retrieval summary, per-area breakdown, invisible documents, and
 * recommendations for improving discoverability.
 */
import { Command } from "commander";
import { existsSync, readFileSync, writeFileSync } from "fs";
import { dirname, join, resolve } from "path";
import { fileURLToPath } from "url";
import { formatDiscoveryMarkdown, generateDiscoveryReport, } from "../pipeline/discovery-report.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..", "..");
const DEFAULT_RESULTS_DIR = join(ROOT, "results", "latest");
/** Resolve `--from-run` to an absolute path to score-summary.json. */
function resolveFromRun(value) {
    if (value === "latest")
        return join(DEFAULT_RESULTS_DIR, "score-summary.json");
    // If the value points at a directory, look for score-summary.json inside it.
    // Otherwise treat it as a direct file path.
    const resolved = resolve(value);
    return resolved.endsWith(".json")
        ? resolved
        : join(resolved, "score-summary.json");
}
export function createDiscoveryReportCommand() {
    return new Command("discovery")
        .description("Generate agent discoverability report from retrieval metrics")
        .option("-a, --area <areas>", "Filter by feature areas (comma-separated)")
        .option("-o, --output <path>", "Write markdown to file instead of stdout")
        .option("--from-run <path>", "Results to read from (`latest`, a results directory, or a direct path to score-summary.json)", "latest")
        .action(async (opts) => {
        const summaryPath = resolveFromRun(opts.fromRun);
        if (!existsSync(summaryPath)) {
            console.error(`❌ Score summary not found: ${summaryPath}`);
            console.error("Run an agentic evaluation first: ailf run --mode agentic");
            process.exit(1);
        }
        const summary = JSON.parse(readFileSync(summaryPath, "utf-8"));
        // Parse area filter
        const areaFilter = opts.area
            ? opts.area.split(",").map((a) => a.trim())
            : undefined;
        const report = generateDiscoveryReport(summary, areaFilter);
        const markdown = formatDiscoveryMarkdown(report);
        if (opts.output) {
            writeFileSync(opts.output, markdown, "utf-8");
            console.log(`✅ Discovery report written to ${opts.output}`);
        }
        else {
            console.log(markdown);
        }
    });
}
