/**
 * Shared helpers for local AI download progress display.
 * Used by Home.tsx, LocalAIStep.tsx, LocalModelPanel.tsx, and LocalAIDownloadSnackbar.tsx.
 */
import type { LocalAiDownloadsProgress, LocalAiStatus } from './tauriCommands';

export const formatBytes = (bytes?: number | null): string => {
  if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return '0 B';
  if (bytes < 1024) return `${Math.round(bytes)} B`;
  const units = ['KB', 'MB', 'GB', 'TB'];
  let value = bytes / 1024;
  let unit = units[0];
  for (let i = 1; i < units.length && value >= 1024; i += 1) {
    value /= 1024;
    unit = units[i];
  }
  return `${value.toFixed(value >= 10 ? 0 : 1)} ${unit}`;
};

export const formatEta = (etaSeconds?: number | null): string => {
  if (typeof etaSeconds !== 'number' || !Number.isFinite(etaSeconds) || etaSeconds <= 0) return '';
  const mins = Math.floor(etaSeconds / 60);
  const secs = etaSeconds % 60;
  if (mins <= 0) return `${secs}s`;
  return `${mins}m ${secs.toString().padStart(2, '0')}s`;
};

export const progressFromStatus = (status: LocalAiStatus | null): number => {
  if (!status) return 0;
  if (typeof status.download_progress === 'number') {
    return Math.max(0, Math.min(1, status.download_progress));
  }
  switch (status.state) {
    case 'ready':
      return 1;
    case 'loading':
      return 0.92;
    case 'downloading':
      return 0.25;
    case 'installing':
      return 0.1;
    case 'idle':
      return 0;
    default:
      return 0;
  }
};

export const progressFromDownloads = (
  downloads: LocalAiDownloadsProgress | null
): number | null => {
  if (!downloads) return null;
  if (typeof downloads.progress !== 'number') return null;
  return Math.max(0, Math.min(1, downloads.progress));
};

export const statusLabel = (state: string): string => {
  switch (state) {
    case 'ready':
      return 'Ready';
    case 'downloading':
      return 'Downloading';
    case 'installing':
      return 'Installing Runtime';
    case 'loading':
      return 'Loading model...';
    case 'degraded':
      return 'Needs Attention';
    case 'disabled':
      return 'Disabled';
    case 'idle':
      return 'Idle';
    default:
      return state;
  }
};
