// lib/reflection/observe.ts

import { publish as publishToAwarenessBus } from '@/lib/awareness';
import { isReflectionEnabled } from './flags';

import type { Signal, EvaluationResult, FeedbackDecision } from './types';

import { ReflectionEvent } from './types';

// Local payload type (reflection layer specific)
type ReflectionPayload =
  | { type: typeof ReflectionEvent.SIGNAL_COMPUTED; payload: Signal }
  | { type: typeof ReflectionEvent.EVALUATION_PERFORMED; payload: EvaluationResult }
  | { type: typeof ReflectionEvent.DECISION_MADE; payload: FeedbackDecision }
  | { type: typeof ReflectionEvent.POLICY_CHANGED; payload: any };

// Generic publisher
function publish(payload: ReflectionPayload) {
  if (!isReflectionEnabled()) return;
  publishToAwarenessBus(payload as any);
}

export function publishSignal(signal: Signal): void {
  publish({ type: ReflectionEvent.SIGNAL_COMPUTED, payload: signal });
}

export function publishEvaluation(evaluation: EvaluationResult): void {
  publish({ type: ReflectionEvent.EVALUATION_PERFORMED, payload: evaluation });
}

export function publishDecision(decision: FeedbackDecision): void {
  publish({ type: ReflectionEvent.DECISION_MADE, payload: decision });
}

export function publishPolicyChange(oldState: any, newState: any): void {
  publish({
    type: ReflectionEvent.POLICY_CHANGED,
    payload: { old: oldState, new: newState },
  });
}
