import axios from 'axios';

const API_BASE = '/api';

const client = axios.create({
  baseURL: API_BASE,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Download API
export const downloadApi = {
  start: (url) => client.post('/download/', { url }),
  getPlatforms: () => client.get('/download/platforms'),
};

// Process API
export const processApi = {
  // Legacy: Full auto processing (not used in manual workflow)
  start: (jobId, options = {}) =>
    client.post('/process/', {
      job_id: jobId,
      bgm_id: options.bgmId || null,
      bgm_volume: options.bgmVolume || 0.3,
      subtitle_style: options.subtitleStyle || null,
      keep_original_audio: options.keepOriginalAudio || false,
      translation_mode: options.translationMode || null,
      use_vocal_separation: options.useVocalSeparation || false,
    }),

  // === Step-by-step Processing API ===

  // Skip trimming and proceed to transcription
  skipTrim: (jobId) => client.post(`/process/${jobId}/skip-trim`),

  // Start transcription step (audio extraction + STT + translation)
  startTranscription: (jobId, options = {}) =>
    client.post(`/process/${jobId}/start-transcription`, {
      translation_mode: options.translationMode || 'rewrite',
      use_vocal_separation: options.useVocalSeparation || false,
    }),

  // Render final video with subtitles and BGM
  render: (jobId, options = {}) =>
    client.post(`/process/${jobId}/render`, {
      bgm_id: options.bgmId || null,
      bgm_volume: options.bgmVolume || 0.3,
      subtitle_style: options.subtitleStyle || null,
      keep_original_audio: options.keepOriginalAudio || false,
      // Intro text overlay (YouTube Shorts thumbnail)
      intro_text: options.introText || null,
      intro_duration: options.introDuration || 0.7,
      intro_font_size: options.introFontSize || 100,
    }),

  // === Other APIs ===

  // Re-run GPT translation
  retranslate: (jobId) => client.post(`/process/${jobId}/retranslate`),

  transcribe: (jobId) => client.post(`/process/${jobId}/transcribe`),
  updateTranscript: (jobId, segments) =>
    client.put(`/process/${jobId}/transcript`, segments),
  // Continue processing for jobs with no audio
  continue: (jobId, options = {}) =>
    client.post(`/process/${jobId}/continue`, {
      job_id: jobId,
      bgm_id: options.bgmId || null,
      bgm_volume: options.bgmVolume || 0.3,
      subtitle_style: options.subtitleStyle || null,
      keep_original_audio: options.keepOriginalAudio || false,
    }),
  // Add manual subtitles
  addManualSubtitle: (jobId, segments) =>
    client.post(`/process/${jobId}/manual-subtitle`, segments),
  // Get video info for trimming
  getVideoInfo: (jobId) => client.get(`/process/${jobId}/video-info`),
  // Get frame at specific timestamp (for precise trimming preview)
  getFrameUrl: (jobId, timestamp) => `${API_BASE}/process/${jobId}/frame?timestamp=${timestamp}`,
  // Trim video (reprocess default: false for manual workflow)
  trim: (jobId, startTime, endTime, reprocess = false) =>
    client.post(`/process/${jobId}/trim`, {
      start_time: startTime,
      end_time: endTime,
      reprocess,
    }),
};

// Jobs API
export const jobsApi = {
  list: (limit = 50) => client.get('/jobs/', { params: { limit } }),
  get: (jobId) => client.get(`/jobs/${jobId}`),
  delete: (jobId) => client.delete(`/jobs/${jobId}`),
  downloadOutput: (jobId) => `${API_BASE}/jobs/${jobId}/download`,
  downloadOriginal: (jobId) => `${API_BASE}/jobs/${jobId}/original`,
  downloadSubtitle: (jobId, format = 'ass') =>
    `${API_BASE}/jobs/${jobId}/subtitle?format=${format}`,
  downloadThumbnail: (jobId) => `${API_BASE}/jobs/${jobId}/thumbnail`,
  // Re-edit completed job (reset to awaiting_review)
  reEdit: (jobId) => client.post(`/jobs/${jobId}/re-edit`),
};

// Thumbnail API
export const thumbnailApi = {
  // Get suggested timestamps for frame selection
  getTimestamps: (jobId, count = 5) =>
    client.get(`/process/${jobId}/thumbnail-timestamps`, { params: { count } }),
  // Generate catchphrase using GPT
  generateCatchphrase: (jobId, style = 'homeshopping') =>
    client.post(`/process/${jobId}/generate-catchphrase`, null, { params: { style } }),
  // Generate thumbnail with text overlay
  generate: (jobId, options = {}) =>
    client.post(`/process/${jobId}/thumbnail`, null, {
      params: {
        timestamp: options.timestamp || 2.0,
        style: options.style || 'homeshopping',
        custom_text: options.customText || null,
        font_size: options.fontSize || 80,
        position: options.position || 'center',
      },
    }),
};

// Fonts API
export const fontsApi = {
  list: () => client.get('/fonts/'),
  recommend: (contentType) => client.get(`/fonts/recommend/${contentType}`),
  categories: () => client.get('/fonts/categories'),
};

// BGM API
export const bgmApi = {
  list: () => client.get('/bgm/'),
  get: (bgmId) => client.get(`/bgm/${bgmId}`),
  upload: (file, name) => {
    const formData = new FormData();
    formData.append('file', file);
    if (name) formData.append('name', name);
    return client.post('/bgm/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
  },
  delete: (bgmId) => client.delete(`/bgm/${bgmId}`),
  // Auto-download BGM from Freesound
  autoDownload: (keywords, maxDuration = 60) =>
    client.post('/bgm/auto-download', {
      keywords,
      max_duration: maxDuration,
      commercial_only: true,
    }),
  // Download default BGM tracks (force re-download if needed)
  initializeDefaults: (force = false) =>
    client.post(`/bgm/defaults/initialize?force=${force}`),
  // Get default BGM list with status
  getDefaultStatus: () => client.get('/bgm/defaults/status'),
};

export default client;
