export function determineDefaultRuntimeFailure(result, summary, firstLine) {
  const fatalRuntimeError = extractDefaultRuntimeFatalError(result.stderr || "", firstLine);
  if (fatalRuntimeError) {
    return `Default runtime uncaught error: ${fatalRuntimeError}`;
  }

  const failedThresholds = extractDefaultRuntimeThresholdFailures(summary);
  if (failedThresholds.length > 0) {
    return `Default runtime thresholds failed: ${failedThresholds.join(", ")}`;
  }

  if (result.exitCode !== 0) {
    return sanitizeDefaultRuntimeExitError(
      result.exitCode,
      result.stderr || result.stdout || "",
      firstLine
    );
  }

  return null;
}

export function extractDefaultRuntimeFatalError(stderr, firstLine) {
  if (!stderr || !/source=stacktrace/.test(stderr)) return null;
  const matched = stderr.match(/Error:\s([^\n]+)/);
  return matched?.[1]?.trim() || firstLine(stderr);
}

export function extractDefaultRuntimeThresholdFailures(summary) {
  const metrics = summary?.metrics;
  if (!metrics || typeof metrics !== "object") return [];

  const failures = [];
  for (const [metricName, metricSummary] of Object.entries(metrics)) {
    const thresholds = metricSummary?.thresholds;
    if (!thresholds || typeof thresholds !== "object") continue;
    for (const [threshold, crossed] of Object.entries(thresholds)) {
      if (crossed === true) {
        failures.push(`${metricName}(${threshold})`);
      }
    }
  }

  return failures.sort();
}

export function sanitizeDefaultRuntimeExitError(exitCode, output, firstLine) {
  const message = firstLine(output);
  if (message) {
    return `Default runtime failed with exit code ${exitCode}: ${message}`;
  }
  return `Default runtime failed with exit code ${exitCode}`;
}
