import type { InferenceProvider } from './InferenceProvider.js';

/**
 * v0.2.3.1 — Mutable provider holder. AiWorker / HealthChecker 가 endpoint 변경 시
 * 새 LocalOllamaProvider 인스턴스를 받도록 indirection layer.
 *
 * 사용 패턴:
 *   const holder = new ProviderHolder(initialProvider);
 *   aiWorker = new AiWorker(repo, holder, opts);
 *   health = new HealthChecker(holder, opts);
 *
 *   // 사용자가 Settings 저장 시:
 *   holder.get().abort?.();       // in-flight 중단 (LocalOllamaProvider 전용)
 *   holder.replace(newProvider);  // 모든 consumer 가 새 인스턴스 사용
 */
export class ProviderHolder {
  private current: InferenceProvider;
  private listeners: Array<(p: InferenceProvider) => void> = [];

  constructor(initial: InferenceProvider) {
    this.current = initial;
  }

  get(): InferenceProvider {
    return this.current;
  }

  replace(next: InferenceProvider): void {
    this.current = next;
    for (const fn of this.listeners) fn(next);
  }

  onReplace(fn: (p: InferenceProvider) => void): void {
    this.listeners.push(fn);
  }
}
