import { createRequire } from "node:module";
import { detectCapabilities } from "../../services/capabilities.js";
import { listProjects } from "../../db/repositories/projects.js";
import { openDatabase } from "../../db/database.js";
const require = createRequire(import.meta.url);
const pkg = require("../../../package.json");
let statusProviders = {};
export function setStatusProviders(providers) {
    statusProviders = providers;
}
function getLastFsSeq(projectId) {
    try {
        const db = openDatabase();
        const row = db.prepare("SELECT last_seq FROM fs_state WHERE project_id = ?").get(projectId);
        return row?.last_seq ?? 0;
    }
    catch {
        return 0;
    }
}
export async function statusRoutes(app) {
    app.get("/status", async (_request, _reply) => {
        const capabilities = detectCapabilities();
        const projects = listProjects();
        const projectList = projects.map((p) => ({
            projectId: p.project_id,
            name: p.name,
            path: p.path,
            watcherRunning: statusProviders.isWatcherRunning?.(p.project_id) ?? false,
            lastFsSeq: getLastFsSeq(p.project_id),
        }));
        const gatewayState = (await statusProviders.getGatewayState?.()) ?? {
            connected: false,
            lastConnectedAt: null,
            lastHeartbeatAt: null,
        };
        const response = {
            version: pkg.version,
            machineKey: statusProviders.getMachineKey?.() ?? null,
            loggedIn: statusProviders.getLoggedIn?.() ?? false,
            user: statusProviders.getUserInfo?.() ?? null,
            gateway: gatewayState,
            opencode: {
                installed: capabilities.hasOpenCode,
                running: statusProviders.isOpenCodeRunning?.() ?? false,
                version: capabilities.openCodeVersion ?? null,
            },
            capabilities,
            projects: projectList,
            lastError: statusProviders.getLastError?.() ?? null,
        };
        return response;
    });
}
//# sourceMappingURL=status.js.map