/**
 * Shared bg-shell event and alert primitives.
 *
 * Extracted from process-manager.js to break the circular dependencies:
 *   output-formatter.js  ↔ process-manager.js  (cycle 8)
 *   readiness-detector.js ↔ process-manager.js  (cycle 9)
 *
 * Both output-formatter.js and readiness-detector.js import addEvent/pushAlert
 * from here instead of from process-manager.js, removing the back-edges.
 *
 * Purpose: append timestamped events to a bg process record and buffer alerts
 * for injection into the next agent context turn.
 *
 * Consumer: output-formatter.js, process-manager.js, readiness-detector.js.
 */

import { MAX_EVENTS } from "./types.js";

/** Pending alerts to inject into the next agent context */
export let pendingAlerts = [];
export const MAX_PENDING_ALERTS = 50;

/** Replace the pendingAlerts array (used by the extension entry point) */
export function setPendingAlerts(alerts) {
	pendingAlerts = alerts;
}

export function addEvent(bg, event) {
	const ev = { ...event, timestamp: Date.now() };
	bg.events.push(ev);
	if (bg.events.length > MAX_EVENTS) {
		bg.events.splice(0, bg.events.length - MAX_EVENTS);
	}
}

export function pushAlert(bg, message) {
	const prefix = bg ? `[bg:${bg.id} ${bg.label}] ` : "";
	pendingAlerts.push(`${prefix}${message}`);
	if (pendingAlerts.length > MAX_PENDING_ALERTS) {
		pendingAlerts.splice(0, pendingAlerts.length - MAX_PENDING_ALERTS);
	}
}
