import { DEFAULT_COMPONENT_CONFIG, appendBounded, applyFilter } from '../types.js';
import { summarizeError } from '../../../utils/error-display.js';
import { logger } from '../../../utils/logger.js';
export class OpsPanel {
    _config;
    _events;
    _audit = [];
    _seq = 0;
    _subscribers = new Set();
    _unsub = null;
    constructor(events, config = DEFAULT_COMPONENT_CONFIG) {
        this._config = config;
        this._events = events;
        this._start();
    }
    _start() {
        this._unsub = this._events.onEnvelope('OPS_AUDIT', (envelope) => {
            this._handleAudit(envelope);
        });
    }
    _handleAudit(envelope) {
        const payload = envelope.payload;
        const record = {
            seq: ++this._seq,
            ts: envelope.ts,
            action: payload.action,
            targetId: payload.targetId,
            targetKind: payload.targetKind,
            reason: payload.reason,
            note: payload.note,
            outcome: payload.outcome,
            errorMessage: payload.errorMessage,
            traceId: envelope.traceId ?? '',
            sessionId: envelope.sessionId ?? '',
        };
        appendBounded(this._audit, record, this._config.bufferLimit);
        this._notify();
    }
    /**
     * Returns a filtered snapshot of the audit log, most recent first.
     */
    getSnapshot(filter) {
        const entries = this._audit.map((r) => ({ ...r }));
        return applyFilter(entries, filter, (e) => e.ts);
    }
    /**
     * Subscribe to data changes. Returns an unsubscribe function.
     */
    subscribe(callback) {
        this._subscribers.add(callback);
        return () => { this._subscribers.delete(callback); };
    }
    /**
     * Dispose the panel, unsubscribing from the event bus.
     */
    dispose() {
        if (this._unsub) {
            this._unsub();
            this._unsub = null;
        }
        this._subscribers.clear();
    }
    _notify() {
        for (const cb of this._subscribers) {
            try {
                cb();
            }
            catch (error) {
                logger.warn('[OpsPanel] subscriber error', { error: summarizeError(error) });
            }
        }
    }
}
