const DIAGNOSTIC_KEY = "sensaBasicDiagnostics";
const MAX_DIAGNOSTICS = 100;

export async function recordDiagnostic(entry) {
  const current = await getDiagnostics();
  const next = [
    ...current,
    {
      time: new Date().toISOString(),
      source: String(entry?.source || "unknown"),
      event: String(entry?.event || "unknown"),
      details: normalizeDetails(entry?.details)
    }
  ].slice(-MAX_DIAGNOSTICS);

  await chrome.storage.local.set({
    [DIAGNOSTIC_KEY]: next
  });
}

export async function getDiagnostics() {
  const stored = await chrome.storage.local.get([DIAGNOSTIC_KEY]);
  return Array.isArray(stored[DIAGNOSTIC_KEY]) ? stored[DIAGNOSTIC_KEY] : [];
}

export async function clearDiagnostics() {
  await chrome.storage.local.remove([DIAGNOSTIC_KEY]);
}

function normalizeDetails(details) {
  if (details == null) {
    return null;
  }
  if (typeof details === "string") {
    return details;
  }
  try {
    return JSON.parse(JSON.stringify(details));
  } catch (error) {
    return String(details);
  }
}
