'use strict';

function isUiRefreshActivitySource(source) {
  const text = String(source || '').toLowerCase();
  return text.includes('ui-refresh');
}

function shouldRecordProviderBusyStatusEvidence(source) {
  return !isUiRefreshActivitySource(source);
}

function positiveMs(value) {
  const n = Number(value || 0);
  return Number.isFinite(n) && n > 0 ? n : 0;
}

function activeTurnLatestEvidenceMs({
  startedAt = 0,
  evidenceAt = 0,
  evidenceSource = '',
  lastActivityAt = 0,
  lastPtyActivityAt = 0,
} = {}) {
  const values = [positiveMs(startedAt), positiveMs(lastActivityAt), positiveMs(lastPtyActivityAt)];
  if (!isUiRefreshActivitySource(evidenceSource)) values.push(positiveMs(evidenceAt));
  return values.reduce((max, value) => Math.max(max, value), 0);
}

module.exports = {
  activeTurnLatestEvidenceMs,
  isUiRefreshActivitySource,
  shouldRecordProviderBusyStatusEvidence,
};
