// lib/reflection/index.ts

import { isReflectionEnabled, isVerbose } from './flags';
import { startIntrospection, stopIntrospection, _resetIntrospection } from './introspection';
import { evaluateSignal } from './evaluator';
import { applyDecisions, makeDecision, _resetFeedbackForTests as _resetFeedback } from './feedback';
import { applyPolicyAdjustments, getPolicyState, _resetPolicyManager } from './policy';
import { addToMemory, _resetMemory } from './memory';
import {
  publishSignal,
  publishEvaluation,
  publishDecision,
  publishPolicyChange,
} from './observe';

let isRunning = false;

function onSignal(signal: any) {
  // This will be updated to handle arrays of signals/evaluations later
  const evaluation = evaluateSignal(signal);
  publishEvaluation(evaluation);
  addToMemory({ evaluation });

  const decisions = makeDecision([evaluation]);
  if (decisions.length > 0) {
      decisions.forEach(decision => {
          publishDecision(decision);
          addToMemory({ decision });
      });
      applyDecisions(decisions);
  }
}

export function startSelfReflection(): void {
  if (isRunning || !isReflectionEnabled()) {
    return;
  }
  if (isVerbose()) {
    console.log('[Reflection] Starting Self-Reflection System...');
  }
  startIntrospection(onSignal);
  isRunning = true;
}

export function stopSelfReflection(): void {
  if (!isRunning) {
    return;
  }
  if (isVerbose()) {
    console.log('[Reflection] Stopping Self-Reflection System...');
  }
  stopIntrospection();
  isRunning = false;
}

export function _resetReflectionSystem(): void {
    stopSelfReflection();
    _resetIntrospection();
    _resetPolicyManager();
    _resetMemory();
    _resetFeedback();
}

// Export all types and public functions
export * from './flags';
export * from './types';
export * from './policy';
export * from './memory';
export * from './evaluator';
export * from './feedback';
