import { renderHudDashboard } from "../commands/hud.js";
export class LiveHudRenderer {
    runId;
    refreshMs;
    timer = null;
    renderSeq = 0;
    constructor(options = {}) {
        this.runId = options.runId;
        this.refreshMs = options.refreshMs ?? 5000;
    }
    async start() {
        await this.renderFrame();
        this.timer = setInterval(() => {
            void this.renderFrame();
        }, this.refreshMs);
        this.timer.unref?.();
    }
    stop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }
    render(state, metrics) {
        if (this.renderSeq >= 10000) {
            this.stop();
            console.warn("[LiveHudRenderer] max render iterations exceeded (10000); stopping to prevent runaway");
            return;
        }
        const seq = ++this.renderSeq;
        void renderHudDashboard({ runId: state?.runId }).then((frame) => {
            if (seq !== this.renderSeq)
                return;
            process.stdout.write(frame + "\n");
        });
        void state;
        void metrics;
    }
    async renderFrame() {
        if (this.renderSeq >= 10000) {
            this.stop();
            console.warn("[LiveHudRenderer] max render iterations exceeded (10000); stopping to prevent runaway");
            return;
        }
        const seq = ++this.renderSeq;
        process.stdout.write("\x1b[2J\x1b[H");
        const frame = await renderHudDashboard({ runId: this.runId, footerRefreshMs: this.refreshMs });
        if (seq !== this.renderSeq)
            return;
        process.stdout.write(frame + "\n");
    }
}
