export const MAX_RESULT_SCREENSHOTS = 9;

function isResultScreenshotKey(value: unknown): value is string {
  return (
    typeof value === "string" &&
    value.startsWith("task-results/") &&
    value.length <= 512
  );
}

export function parseResultScreenshotKeys(value: unknown): string[] {
  const text = String(value ?? "").trim();
  if (!text) return [];
  if (isResultScreenshotKey(text)) return [text];
  try {
    const parsed = JSON.parse(text) as unknown;
    if (!Array.isArray(parsed)) return [];
    return [...new Set(parsed.filter(isResultScreenshotKey))].slice(
      0,
      MAX_RESULT_SCREENSHOTS,
    );
  } catch {
    return [];
  }
}

export function serializeResultScreenshotKeys(keys: string[]) {
  return JSON.stringify(
    [...new Set(keys.filter(isResultScreenshotKey))].slice(
      0,
      MAX_RESULT_SCREENSHOTS,
    ),
  );
}
