export type PreviewDiagnosticLevel = 'log' | 'info' | 'warn' | 'error';

export type PreviewDiagnosticEntry = Readonly<{
  level: PreviewDiagnosticLevel;
  text: string;
  recordedAt: number;
}>;

const MAX_PROJECT_DIAGNOSTICS = 500;
const diagnosticsByProject = new Map<string, PreviewDiagnosticEntry[]>();

function cleanProjectId(projectId: string): string {
  return String(projectId || '').trim().toLowerCase();
}

export function recordPreviewDiagnostic(projectId: string, input: { level: PreviewDiagnosticLevel; text: string }): void {
  const id = cleanProjectId(projectId);
  const text = String(input.text || '').trim().slice(0, 8_000);
  if (!id || !text) return;
  const current = diagnosticsByProject.get(id) ?? [];
  current.push(Object.freeze({ level: input.level, text, recordedAt: Date.now() }));
  if (current.length > MAX_PROJECT_DIAGNOSTICS) current.splice(0, current.length - MAX_PROJECT_DIAGNOSTICS);
  diagnosticsByProject.set(id, current);
}

export function recentPreviewDiagnostics(projectId: string, limit = 100): PreviewDiagnosticEntry[] {
  const id = cleanProjectId(projectId);
  if (!id) return [];
  const current = diagnosticsByProject.get(id) ?? [];
  return current.slice(-Math.max(1, Math.min(MAX_PROJECT_DIAGNOSTICS, Math.trunc(limit) || 100)));
}

export function clearPreviewDiagnostics(projectId: string): void {
  const id = cleanProjectId(projectId);
  if (id) diagnosticsByProject.delete(id);
}
