/**
 * readiness-report command — generates a launch readiness checklist
 * for a given feature area.
 *
 * Combines threshold evaluation, ceiling decomposition, and gap analysis
 * into a single actionable report.
 *
 */
import { Command } from "commander";
import { existsSync, readFileSync, readdirSync, writeFileSync } from "fs";
import { dirname, join, resolve } from "path";
import { fileURLToPath } from "url";
import { ConfigNotFoundError, loadConfigFile, } from "../pipeline/compiler/config-loader.js";
import { formatReadinessMarkdown, generateReadinessReport, } from "../pipeline/readiness-report.js";
import { ThresholdConfigSchema, } from "../pipeline/schemas.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..", "..");
const DEFAULT_RESULTS_DIR = join(ROOT, "results", "latest");
// thresholds loaded via loadConfigFile below
const BASELINES_DIR = join(ROOT, "results", "baselines");
/** Resolve `--from-run` to an absolute results directory. */
function resolveFromRun(value) {
    if (value === "latest")
        return DEFAULT_RESULTS_DIR;
    return resolve(value);
}
export function createReadinessReportCommand() {
    return new Command("readiness")
        .description("Generate launch readiness report for a feature area")
        .requiredOption("-a, --area <area>", "Feature area to evaluate (required)")
        .option("--from-run <path>", "Results directory to read from (`latest` or a path to a results directory containing score-summary.json)", "latest")
        .option("-H, --history", "Include historical progress from baselines", false)
        .option("-o, --output <path>", "Write markdown to file instead of stdout")
        .action(async (opts) => {
        const resultsDir = resolveFromRun(opts.fromRun);
        const scoreSummaryPath = join(resultsDir, "score-summary.json");
        const gapAnalysisPath = join(resultsDir, "gap-analysis.json");
        // Load score summary
        if (!existsSync(scoreSummaryPath)) {
            console.error(`❌ Score summary not found at ${scoreSummaryPath}. Run \`ailf run\` first or pass --from-run <path>.`);
            process.exit(1);
        }
        const scoreSummary = JSON.parse(readFileSync(scoreSummaryPath, "utf-8"));
        // Load threshold config
        let parsedThresholds;
        try {
            parsedThresholds = loadConfigFile("thresholds", ROOT).data;
        }
        catch (err) {
            if (err instanceof ConfigNotFoundError) {
                console.error("❌ Threshold config not found in config/.");
            }
            else {
                console.error(`❌ Failed to load threshold config: ${err instanceof Error ? err.message : err}`);
            }
            process.exit(1);
        }
        const thresholdResult = ThresholdConfigSchema.safeParse(parsedThresholds);
        if (!thresholdResult.success) {
            const messages = thresholdResult.error.issues
                .map((i) => `  ${i.path.join(".")}: ${i.message}`)
                .join("\n");
            console.error(`❌ Invalid thresholds.yaml:\n${messages}`);
            process.exit(1);
        }
        const thresholdConfig = thresholdResult.data;
        // Load gap analysis (optional)
        let gapAnalysis;
        if (existsSync(gapAnalysisPath)) {
            gapAnalysis = JSON.parse(readFileSync(gapAnalysisPath, "utf-8"));
        }
        const history = [];
        if (opts.history && existsSync(BASELINES_DIR)) {
            const files = readdirSync(BASELINES_DIR)
                .filter((f) => f.endsWith(".json"))
                .sort();
            for (const file of files) {
                try {
                    const raw = readFileSync(join(BASELINES_DIR, file), "utf-8");
                    const data = JSON.parse(raw);
                    const areaScore = data.scores?.find((s) => s.feature === opts.area);
                    if (!areaScore)
                        continue;
                    const nameWithoutExt = file.replace(/\.json$/, "");
                    const parts = nameWithoutExt.split("_");
                    const tag = parts.length > 4 ? parts.slice(4).join("_") : undefined;
                    history.push({
                        score: areaScore.totalScore,
                        tag,
                        timestamp: data.timestamp ?? nameWithoutExt,
                    });
                }
                catch {
                    // Skip malformed baseline files
                }
            }
        }
        // Generate report
        const report = generateReadinessReport({
            area: opts.area,
            gapAnalysis,
            history,
            scoreSummary,
            thresholdConfig,
        });
        // Format and output
        const markdown = formatReadinessMarkdown(report);
        if (opts.output) {
            writeFileSync(opts.output, markdown, "utf-8");
            console.error(`✅ Readiness report written to ${opts.output}`);
        }
        else {
            console.log(markdown);
        }
        // Exit with non-zero if not ready
        if (!report.pass) {
            process.exit(1);
        }
    });
}
