import { CONTROL_PLANE_HOST, CONTROL_PLANE_PORT } from "@pocketcoder/shared";
import { isDaemonRunning } from "./start.js";
/**
 * Handle the `pocketcoder machine label <text>` CLI command.
 * Sets the machine label via the daemon's control plane.
 */
export async function machineLabelCommand(text, opts) {
    // --show flag: display current label
    if (opts.show) {
        await showLabel();
        return;
    }
    await setLabel(text);
}
async function showLabel() {
    const running = await isDaemonRunning();
    if (!running) {
        console.log("Daemon is not running. Start the daemon first.");
        process.exitCode = 1;
        return;
    }
    try {
        const url = `http://${CONTROL_PLANE_HOST}:${CONTROL_PLANE_PORT}/machine/label`;
        const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
        if (!response.ok) {
            console.error(`Failed to get machine label: HTTP ${response.status}`);
            process.exitCode = 1;
            return;
        }
        const body = (await response.json());
        if (body.label) {
            console.log(`Current label: ${body.label}`);
        }
        else {
            console.log("No custom label set (using default)");
        }
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        console.error(`Failed to get machine label: ${message}`);
        process.exitCode = 1;
    }
}
async function setLabel(text) {
    if (!text || text.trim().length === 0) {
        console.error("Label text is required");
        process.exitCode = 1;
        return;
    }
    const running = await isDaemonRunning();
    if (!running) {
        console.log("Daemon is not running. Start the daemon first.");
        process.exitCode = 1;
        return;
    }
    try {
        const url = `http://${CONTROL_PLANE_HOST}:${CONTROL_PLANE_PORT}/machine/label`;
        const response = await fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ label: text.trim() }),
            signal: AbortSignal.timeout(5000),
        });
        if (!response.ok) {
            const body = (await response.json());
            console.error(`Failed to set machine label: ${body.error ?? `HTTP ${response.status}`}`);
            process.exitCode = 1;
            return;
        }
        console.log(`Machine label updated: ${text.trim()}`);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        console.error(`Failed to set machine label: ${message}`);
        process.exitCode = 1;
    }
}
//# sourceMappingURL=machine.js.map