import { CONTROL_PLANE_HOST, CONTROL_PLANE_PORT } from "@pocketcoder/shared";
import { isDaemonRunning } from "./start.js";
import { readPidFile } from "../../utils/pid.js";
/**
 * Handle the `pocketcoder status` CLI command.
 * Queries the /status endpoint and displays formatted output.
 */
export async function statusCommand() {
    const running = await isDaemonRunning();
    if (!running) {
        console.log("Daemon: not running");
        return;
    }
    try {
        const pid = await readPidFile();
        const url = `http://${CONTROL_PLANE_HOST}:${CONTROL_PLANE_PORT}/status`;
        const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
        if (!response.ok) {
            console.error(`Failed to query status: HTTP ${response.status}`);
            process.exitCode = 1;
            return;
        }
        const status = (await response.json());
        // Daemon line
        console.log(`Daemon: running (pid ${pid})`);
        // Gateway line - connection status is verified via real-time ping
        if (status.gateway.connected) {
            console.log(`Gateway: connected (verified)`);
        }
        else {
            console.log(`Gateway: disconnected`);
        }
        // User line
        if (status.loggedIn && status.machineKey) {
            const userDisplay = status.user?.username ?? status.user?.email ?? "logged in";
            const provider = status.user?.provider ? ` (${status.user.provider})` : "";
            console.log(`User:   ${userDisplay}${provider}`);
        }
        else {
            console.log(`User:   not logged in`);
        }
        // OpenCode line
        if (status.opencode?.installed) {
            const runningState = status.opencode.running ? "running" : "not running";
            const version = status.opencode.version ?? "unknown";
            console.log(`OpenCode: ${runningState} (${version})`);
        }
        else {
            console.log(`OpenCode: not installed`);
        }
        // Projects section
        const total = status.projects.length;
        const watching = status.projects.filter((p) => p.watcherRunning).length;
        console.log(`Projects: ${total} registered, ${watching} watching`);
        if (status.projects.length > 0) {
            for (const project of status.projects) {
                const watchStatus = project.watcherRunning ? "watching" : "idle";
                console.log(`  - ${project.name} (${watchStatus})`);
            }
        }
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        console.error(`Failed to query status: ${message}`);
        process.exitCode = 1;
    }
}
//# sourceMappingURL=status.js.map