import api from './api';

export interface QueueStats {
  waiting: number;
  active: number;
  completed: number;
  failed: number;
  delayed: number;
  paused: number;
}

export interface JobHistoryEntry {
  id: string;
  name: string;
  data: Record<string, unknown>;
  timestamp: number;
  finishedOn?: number;
  failedReason?: string;
  returnvalue?: unknown;
  progress?: number;
  attemptsMade?: number;
}

export type JobStatus = 'completed' | 'failed' | 'running';

export const JOB_LABELS: Record<string, string> = {
  scan_library: 'Library Scan',
  metadata_refresh: 'Metadata Refresh',
  artist_similarity: 'Artist Similarity',
  artist_image: 'Artist Image',
  album_cover: 'Album Cover',
  audio_analysis: 'Audio Analysis',
  integrity_sweep: 'Integrity Sweep',
  cleanup_sweep: 'Cleanup Sweep',
  cleanup: 'Cleanup',
  reindex_tracks: 'Reindex Tracks',
  reprocess_artists: 'Reprocess Artists',
};

/** Human-readable summary of job payload data for display in the list. */
export function getJobDataSummary(name: string, data: Record<string, unknown>): string {
  switch (name) {
    case 'scan_library':
      return `📁 ${String(data.directory ?? '?')}`;
    case 'metadata_refresh':
      return `🎵 track: ${String(data.trackId ?? '?').slice(0, 12)} · ${String(data.refreshType ?? '?')}`;
    case 'audio_analysis':
      return `🎵 track: ${String(data.trackId ?? '?').slice(0, 12)} · features: ${Array.isArray(data.features) ? data.features.length : '?'}`;
    case 'artist_similarity':
      return `👤 artist: ${String(data.artistId ?? '?').slice(0, 12)}`;
    case 'artist_image':
      return `🖼️ artist: ${String(data.artistId ?? '?').slice(0, 12)}`;
    case 'album_cover':
      return `💿 album: ${String(data.albumId ?? '?').slice(0, 12)}`;
    case 'integrity_sweep':
      return `🔍 ${String(data.reason ?? 'scheduled')}`;
    case 'cleanup_sweep':
      return `🧹 ${String(data.reason ?? 'scheduled')}`;
    case 'cleanup':
      return `🧹 ${String(data.reason ?? '?')} · ${Array.isArray(data.targetFiles) ? `${data.targetFiles.length} files` : '?'}`;
    case 'reindex_tracks':
      return `🔄 all tracks → Typesense`;
    case 'reprocess_artists':
      return `👤 batch=${String(data.batchSize ?? '?')} offset=${String(data.offset ?? '?')}`;
    default:
      return '';
  }
}

/** Human-readable detail lines for the expanded view. */
export function getJobDataDetails(name: string, data: Record<string, unknown>): { label: string; value: string }[] {
  const details: { label: string; value: string }[] = [];

  switch (name) {
    case 'scan_library':
      details.push({ label: 'Directory', value: String(data.directory ?? '?') });
      break;
    case 'metadata_refresh':
      details.push({ label: 'Track ID', value: String(data.trackId ?? '?') });
      details.push({ label: 'Refresh Type', value: String(data.refreshType ?? '?') });
      break;
    case 'audio_analysis':
      details.push({ label: 'Track ID', value: String(data.trackId ?? '?') });
      details.push({ label: 'Features', value: Array.isArray(data.features) ? data.features.join(', ') : '?' });
      break;
    case 'artist_similarity':
      details.push({ label: 'Artist ID', value: String(data.artistId ?? '?') });
      break;
    case 'artist_image':
      details.push({ label: 'Artist ID', value: String(data.artistId ?? '?') });
      break;
    case 'album_cover':
      details.push({ label: 'Album ID', value: String(data.albumId ?? '?') });
      break;
    case 'integrity_sweep':
      details.push({ label: 'Reason', value: String(data.reason ?? 'scheduled') });
      break;
    case 'cleanup_sweep':
      details.push({ label: 'Reason', value: String(data.reason ?? 'scheduled') });
      break;
    case 'cleanup':
      details.push({ label: 'Reason', value: String(data.reason ?? '?') });
      details.push({ label: 'Target Files', value: Array.isArray(data.targetFiles) ? data.targetFiles.join(', ') : '?' });
      break;
    case 'reprocess_artists':
      details.push({ label: 'Batch Size', value: String(data.batchSize ?? '?') });
      details.push({ label: 'Offset', value: String(data.offset ?? '?') });
      break;
  }

  return details;
}

export function getJobStatus(job: JobHistoryEntry): JobStatus {
  if (!job.finishedOn && !job.failedReason) return 'running';
  if (job.failedReason) return 'failed';
  return 'completed';
}

export const jobsService = {
  async getQueueStats(): Promise<QueueStats> {
    const response = await api.get('/admin/queue-stats');
    return response.data;
  },

  async getJobHistory(limit = 100): Promise<JobHistoryEntry[]> {
    const response = await api.get('/admin/job-history', { params: { limit } });
    return response.data;
  },

  async triggerScan(directory: string) {
    const response = await api.post('/admin/scan', { directory });
    return response.data;
  },

  async triggerReindex() {
    const response = await api.post('/admin/reindex-tracks');
    return response.data;
  },
};