// SF Extension — Notify Interceptor
// Wraps ctx.ui.notify() in-place to persist every notification through the
// notification store. Uses a WeakSet to prevent double-wrapping and handle
// UI context replacement on /reload gracefully.

import { appendNotification } from "../notification-store.js";
import { logWarning } from "../workflow-logger.js";

// Track which ui context objects have been wrapped to prevent double-install.
// WeakSet allows GC to collect replaced uiContext instances after /reload.
const _wrappedContexts = new WeakSet();
/**
 * Install the notify interceptor on a context's UI object.
 * Mutates ctx.ui.notify in place — the original is called after persistence.
 * Safe to call multiple times; no-ops if already installed on the same ui object.
 *
 * Optional third-arg metadata for durable hygiene:
 * - dedupe_key — stable merge identity across wording/timer drift
 * - noticeKind — NOTICE_KIND.* (system_notice, tool_notice, …)
 * - merge — false to force a new JSONL row even when duplicate
 */
export function installNotifyInterceptor(ctx) {
	if (_wrappedContexts.has(ctx.ui)) return;
	const originalNotify = ctx.ui.notify.bind(ctx.ui);
	ctx.ui.notify = (message, type, metadata) => {
		try {
			appendNotification(message, type ?? "info", "notify", metadata);
		} catch (err) {
			// Non-fatal — never let persistence break the UI.
			// Include a correlation ID (timestamp + truncated message) so the
			// failure can be matched against the notification that was dropped.
			const correlationId = `${Date.now()}-${message.slice(0, 40).replace(/\s+/g, "_")}`;
			logWarning(
				"scaffold",
				`notification persistence failed (non-fatal) [corr:${correlationId}]: ${err.message}`,
			);
		}
		originalNotify(message, type, metadata);
	};
	_wrappedContexts.add(ctx.ui);
}
