import type { AutoResumeSummary, ContinuityWorkerView } from './ui-model.js';

export function relativeAge(value: string | null, currentTime = Date.now()): string {
  if (!value) return 'No durable progress yet';
  const parsed = Date.parse(value);
  if (!Number.isFinite(parsed)) return 'Progress time unavailable';
  const seconds = Math.max(0, Math.floor((currentTime - parsed) / 1000));
  if (seconds < 60) return `${seconds}s ago`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86_400) return `${Math.floor(seconds / 3600)}h ago`;
  return `${Math.floor(seconds / 86_400)}d ago`;
}

export function autoResumeLabel(summary: AutoResumeSummary): string {
  switch (summary) {
    case 'on': return 'On for managed workers';
    case 'off': return 'Off for managed workers';
    case 'mixed': return 'Mixed worker policies';
    case 'unavailable': return 'Backend policy unavailable';
  }
}

export function policyLabel(worker: ContinuityWorkerView): string {
  if (worker.policyMode === null) return 'Backend policy unavailable';
  const mode = worker.policyMode === 'auto' ? 'Auto Resume On' : 'Auto Resume Off';
  if (worker.policySource === 'worker') return `${mode} · Worker override`;
  if (worker.policySource === 'run') return `${mode} · Run default`;
  if (worker.policySource === 'default') return `${mode} · System default`;
  return `${mode} · Policy source unavailable`;
}

export function workerSecondaryName(worker: ContinuityWorkerView): string | null {
  if (worker.hierarchicalName && worker.hierarchicalName !== worker.label) return worker.hierarchicalName;
  return null;
}

export function attemptSummary(worker: ContinuityWorkerView): string {
  const parts: string[] = [];
  parts.push(worker.attemptNumber === null ? 'Attempt unavailable' : `Attempt ${worker.attemptNumber}`);
  if (worker.autoResumeCount !== null) parts.push(`${worker.autoResumeCount} auto resumes`);
  parts.push(relativeAge(worker.lastProgressAt));
  return parts.join(' · ');
}

export function stallDescription(worker: ContinuityWorkerView): string {
  if (worker.stallState === 'unavailable') return 'Stall metadata is not exposed by the current backend UI contract.';
  if (worker.stallState === 'none') return 'No stall warning reported.';
  const attempts = worker.noProgressAttempts === null ? 'No-progress attempt count unavailable' : `${worker.noProgressAttempts} attempts without durable progress`;
  if (worker.stallState === 'paused') return `Paused for stall · ${attempts} · ${relativeAge(worker.lastProgressAt)}`;
  return `Worker appears stuck · ${attempts} · ${relativeAge(worker.lastProgressAt)}`;
}

export function blockReasonLabel(worker: ContinuityWorkerView): string {
  if (worker.blockReason) return worker.blockReason;
  if (worker.needsUser) return 'Backend reports that user input is required; detailed reason is unavailable.';
  if (worker.statusLabel === 'Waiting') return 'Backend reports a dependency wait; detailed reason is unavailable.';
  if (worker.statusLabel === 'Paused' && worker.pauseReason === 'stall') return 'Paused by the stall guard.';
  if (worker.statusLabel === 'Paused' && worker.pauseReason === 'error') return 'Paused after an execution error.';
  if (worker.statusLabel === 'Paused') return 'Paused by operator or policy; detailed reason is unavailable.';
  return '—';
}

export function overlayCollapsedLines(worker: ContinuityWorkerView): { primary: string; detail: string } {
  const primary = worker.policyMode === 'auto' ? 'Orchestrated · Auto Resume' : 'Orchestrated';
  const attempt = worker.attemptNumber === null ? '' : ` · Attempt ${worker.attemptNumber}`;
  const status = worker.statusLabel === 'Resuming' ? 'Continuing' : worker.statusLabel;
  return { primary, detail: `${status}${attempt}` };
}
