// packages/plugin-awf/src/commands/update.ts
// AWF Update Command — Version check & upgrade redirect
// v2.0.0: Real version comparison across CLI, AWF, HSA
import pc from "picocolors";
import * as prompts from "@clack/prompts";
import { AWF_VERSION } from "../constants.js";
import { getInstalledHSAVersion, checkHSAUpdate } from "./install-hsa.js";
export const updateFlags = {
    check: {
        type: "boolean",
        description: "Check for updates without installing",
        alias: "c",
        default: false,
    },
};
/**
 * Format version comparison: current → latest (with color)
 */
function formatVersion(current, latest) {
    if (!latest || latest === "unknown") {
        return `${pc.cyan(current)} ${pc.dim("(unable to check)")}`;
    }
    if (current === latest || current === "unknown") {
        return `${pc.green(`v${latest}`)} ${pc.dim("✔ up to date")}`;
    }
    return `${pc.yellow(`v${current}`)} → ${pc.green(`v${latest}`)} ${pc.cyan("update available")}`;
}
export async function updateCommand(_args, flags) {
    const checkOnly = flags.check;
    const spinner = prompts.spinner();
    // Always check versions (--check or default)
    spinner.start("Checking for updates...");
    let latestCli = "unknown";
    let latestAwf = "unknown";
    let currentCli = "unknown";
    const installedHsa = getInstalledHSAVersion() || "not installed";
    // Parallel fetch all latest versions from npm registry
    try {
        const [cliRes, awfRes] = await Promise.all([
            fetch("https://registry.npmjs.org/@nockdev/cli/latest", {
                signal: AbortSignal.timeout(5_000),
            }),
            fetch("https://registry.npmjs.org/@nockdev/awf/latest", {
                signal: AbortSignal.timeout(5_000),
            }),
        ]);
        if (cliRes.ok)
            latestCli = (await cliRes.json()).version;
        if (awfRes.ok)
            latestAwf = (await awfRes.json()).version;
    }
    catch { /* timeout or network error */ }
    // Check HSA via dedicated function
    let latestHsa = "unknown";
    try {
        const hsaCheck = await checkHSAUpdate();
        if (hsaCheck.latest)
            latestHsa = hsaCheck.latest;
    }
    catch { /* ignore */ }
    // Get current CLI version (works regardless of package manager)
    try {
        const { execSync } = await import("node:child_process");
        currentCli = execSync("nock --version", {
            encoding: "utf-8",
            timeout: 5_000,
            stdio: ["pipe", "pipe", "pipe"],
        }).trim();
    }
    catch {
        currentCli = "unknown";
    }
    spinner.stop("Version check complete");
    // Display version comparison table
    console.log();
    console.log(pc.bold("  Package Versions:"));
    console.log(`  CLI  (@nockdev/cli):  ${formatVersion(currentCli, latestCli)}`);
    console.log(`  AWF  (@nockdev/awf):  ${formatVersion(AWF_VERSION, latestAwf)}`);
    console.log(`  HSA  (@nockdev/hsa):  ${formatVersion(installedHsa, latestHsa)}`);
    // Check if any updates available
    const hasUpdates = (latestCli !== "unknown" && currentCli !== latestCli) ||
        (latestAwf !== "unknown" && AWF_VERSION !== latestAwf) ||
        (latestHsa !== "unknown" && installedHsa !== latestHsa);
    if (checkOnly || !hasUpdates) {
        if (!hasUpdates) {
            console.log();
            console.log(pc.green("  ✔ All packages are up to date!"));
        }
        console.log();
        console.log(pc.dim("  Run ") + pc.cyan("nock upgrade") + pc.dim(" to upgrade all components."));
        console.log();
        return;
    }
    // Offer to run full upgrade
    console.log();
    console.log(`  Run ${pc.cyan("nock upgrade")} to upgrade all components.`);
    console.log();
}
