// lib/reflection/types.ts

// --- SIGNALS ---
export const SIGNALS = {
  WINDOW_CHURN: 'WINDOW_CHURN',
  FOCUS_STABILITY: 'FOCUS_STABILITY',
  LATENCY_SUMMARY: 'LATENCY_SUMMARY',
  IDLE_RATIO: 'IDLE_RATIO',
  WINDOW_LIFETIME: 'WINDOW_LIFETIME',
} as const;

export type SignalType = (typeof SIGNALS)[keyof typeof SIGNALS];

// --- POLICY NAMES ---
export const POLICY_NAMES = {
  THROTTLE_WINDOWS: 'THROTTLE_WINDOWS',
  DEFER_ANIMATIONS: 'DEFER_ANIMATIONS',
  ADJUST_PREFETCH: 'ADJUST_PREFETCH',
  TUNE_FOCUS_TIMEOUT: 'TUNE_FOCUS_TIMEOUT',
} as const;

export type PolicyName = (typeof POLICY_NAMES)[keyof typeof POLICY_NAMES];

export type EvalStatus = 'NORMAL' | 'WARNING' | 'CRITICAL';

// -------------------------
// Signal + Evaluation Types
// -------------------------

export interface IntrospectionSignal {
  type: SignalType;
  value: number;
  timestamp: number;
  metadata?: Record<string, any>;
}

// Backwards-compatible alias expected by some modules/tests
export type Signal = IntrospectionSignal;

export interface SignalEvaluator {
  signal: SignalType;
  slos: { threshold: number; status: EvalStatus }[];
}

// -------------------------
// Reflection Snapshot
// -------------------------

export interface ReflectionSnapshot {
  timestamp: number;
  evaluationCount: number;
  appliedDecisions: string[];
  metrics: { churn: number; focus: number };
}

// Memory entry used by in-memory buffer
export interface ReflectionMemoryEntry {
  sequence: number;
  timestamp: number;
  evaluation?: EvaluationResult;
  decision?: FeedbackDecision;
}

export interface EvaluationResult {
  signal: IntrospectionSignal;
  status: EvalStatus;
  slo: { threshold: number; status: EvalStatus } | null;
  timestamp: number;
}

export interface FeedbackDecision {
  ts: number;
  cause: EvaluationResult[];
  action: 'THROTTLE_WINDOWS' | 'DEFER_ANIM' | 'ADJUST_PREFETCH' | 'TUNE_FOCUS_TIMEOUT' | 'NOOP';
  params?: Record<string, any>;
  mode: 'PROPOSED' | 'DRY_RUN' | 'APPLIED';
}

export interface PolicyAdjustment {
  policyName: PolicyName;
  newValue: number | boolean;
  reason: string;
}

// -------------------------
// Policy (Reflection-Layer Alias)
// -------------------------

// Generic policy shape used only for reflection events.
// The actual policy engine may define richer schemas elsewhere.
export type Policy = Record<string, any>;
export type PolicyState = Policy;

// -------------------------
// Reflection Events
// -------------------------

export const ReflectionEvent = {
  SIGNAL_COMPUTED: 'SIGNAL_COMPUTED',
  EVALUATION_PERFORMED: 'EVALUATION_PERFORMED',
  DECISION_MADE: 'DECISION_MADE',
  POLICY_CHANGED: 'POLICY_CHANGED',
} as const;

export type ReflectionEventType = (typeof ReflectionEvent)[keyof typeof ReflectionEvent];
