import type { MediaProbe } from '../media';

export type AssetPhase = 'queued' | 'probing' | 'ready' | 'error';

export interface ImportedMediaAsset {
  id: string;
  file: File;
  objectUrl: string;
  phase: AssetPhase;
  probe?: MediaProbe;
  rawProbe?: string;
  error?: string;
}

export interface ExportResult {
  id: string;
  name: string;
  mimeType: string;
  bytes: number;
  blob: Blob;
  objectUrl: string;
  createdAt: string;
}

export type WorkspaceMode = 'quick-convert' | 'edit';

export function createAsset(file: File): ImportedMediaAsset {
  return {
    id: crypto.randomUUID(),
    file,
    objectUrl: URL.createObjectURL(file),
    phase: 'queued',
  };
}

export function formatBytes(bytes: number): string {
  if (!Number.isFinite(bytes) || bytes < 0) return 'Unknown size';
  if (bytes < 1_000) return `${bytes} B`;
  const units = ['kB', 'MB', 'GB', 'TB'];
  let value = bytes / 1_000;
  let unit = units[0];
  for (let index = 1; index < units.length && value >= 1_000; index += 1) {
    value /= 1_000;
    unit = units[index];
  }
  return `${value.toFixed(value >= 10 ? 1 : 2)} ${unit}`;
}

export function formatDuration(seconds: number | undefined): string {
  if (seconds === undefined || !Number.isFinite(seconds)) return 'Unknown';
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remaining = seconds % 60;
  return [
    ...(hours > 0 ? [String(hours)] : []),
    String(minutes).padStart(hours > 0 ? 2 : 1, '0'),
    remaining.toFixed(2).padStart(5, '0'),
  ].join(':');
}

export function releaseAssets(assets: readonly ImportedMediaAsset[]): void {
  for (const asset of assets) URL.revokeObjectURL(asset.objectUrl);
}

export function releaseResults(results: readonly ExportResult[]): void {
  for (const result of results) URL.revokeObjectURL(result.objectUrl);
}
