/**
 * Log relay: in-memory tail buffer per host for logData SSE events.
 *
 * - 2k-line tail per host for late joiners
 * - Relays /api/events logData into control_log frames
 * - Source filter: proxy | upstream | model
 */

const MAX_LOG_LINES = 2000;

export interface LogLine {
  providerId: string;
  source: 'proxy' | 'upstream' | 'model';
  line: string;
  ts: Date;
}

export class LogRelay {
  private tails: Map<string, LogLine[]> = new Map();

  /**
   * Append a log line to the per-host tail buffer.
   */
  append(providerId: string, source: 'proxy' | 'upstream' | 'model', line: string): void {
    let tail = this.tails.get(providerId);
    if (!tail) {
      tail = [];
      this.tails.set(providerId, tail);
    }
    tail.push({ providerId, source, line, ts: new Date() });
    // Trim to max lines
    while (tail.length > MAX_LOG_LINES) {
      tail.shift();
    }
  }

  /**
   * Get the tail buffer for a host (for late joiners).
   */
  getTail(providerId: string): LogLine[] {
    return this.tails.get(providerId) ?? [];
  }

  /**
   * Get all tails (for snapshot-on-join).
   */
  getAllTails(): LogLine[] {
    const all: LogLine[] = [];
    for (const tail of this.tails.values()) {
      all.push(...tail);
    }
    return all;
  }

  /**
   * Get unique source values across all logs.
   */
  getSources(): string[] {
    const sources = new Set<string>();
    for (const tail of this.tails.values()) {
      for (const entry of tail) {
        sources.add(entry.source);
      }
    }
    return Array.from(sources);
  }
}
