// src/core/eval/strategy/sessionActivation.ts
// Session-scoped strategy and middleware activation state shared by REPL + primitives.

export type RuntimeMiddlewareRef = {
  name: string;
  config: Record<string, unknown>;
};

function normalizeName(name: string): string {
  const cleaned = name.replace(/'/g, "").trim();
  if (cleaned.startsWith("middleware/")) {
    return cleaned.slice("middleware/".length);
  }
  return cleaned;
}

let sessionStrategy: string | undefined;
const sessionSecurity = new Map<string, RuntimeMiddlewareRef>();
const sessionObservation = new Map<string, RuntimeMiddlewareRef>();

export function setSessionStrategy(name: string): void {
  const normalized = normalizeName(name);
  sessionStrategy = normalized || undefined;
}

export function getSessionStrategy(): string | undefined {
  return sessionStrategy;
}

export function clearSessionStrategy(): void {
  sessionStrategy = undefined;
}

export function useSessionSecurity(name: string, config: Record<string, unknown> = {}): void {
  const normalized = normalizeName(name);
  if (!normalized) return;
  sessionSecurity.set(normalized, { name: normalized, config: { ...config } });
}

export function removeSessionSecurity(name: string): boolean {
  const normalized = normalizeName(name);
  return sessionSecurity.delete(normalized);
}

export function listSessionSecurity(): RuntimeMiddlewareRef[] {
  return Array.from(sessionSecurity.values()).map((entry) => ({
    name: entry.name,
    config: { ...entry.config },
  }));
}

export function useSessionObservation(name: string, config: Record<string, unknown> = {}): void {
  const normalized = normalizeName(name);
  if (!normalized) return;
  sessionObservation.set(normalized, { name: normalized, config: { ...config } });
}

export function removeSessionObservation(name: string): boolean {
  const normalized = normalizeName(name);
  return sessionObservation.delete(normalized);
}

export function listSessionObservation(): RuntimeMiddlewareRef[] {
  return Array.from(sessionObservation.values()).map((entry) => ({
    name: entry.name,
    config: { ...entry.config },
  }));
}

export function clearSessionActivations(): void {
  sessionStrategy = undefined;
  sessionSecurity.clear();
  sessionObservation.clear();
}
