import { getHeaders } from 'hooks/useClient';

const API_URL = '/api';

export type FileType = 'markdown' | 'audio' | 'video' | 'image' | 'pdf' | 'code' | 'archive' | 'text';

export const ARCHIVE_EXTS = ['zip', 'tar', 'gz', 'tgz', 'bz2', 'tbz2', 'xz', 'txz', 'zst', '7z', 'rar'];
export const AUDIO_EXTS = ['mp3', 'wav', 'flac', 'ogg', 'oga', 'opus', 'aac', 'm4a', 'wma'];
export const NATIVE_VIDEO_EXTS = ['mp4', 'm4v', 'webm', 'ogv', 'mov'];
export const IMAGE_EXTS = [
  'jpg',
  'jpeg',
  'png',
  'gif',
  'webp',
  'svg',
  'bmp',
  'ico',
  'tiff',
  'tif',
  'avif',
  'heic',
  'heif',
  'jfif',
  'apng',
];

export const EXT_TO_LANG: Record<string, string> = {
  js: 'javascript',
  mjs: 'javascript',
  cjs: 'javascript',
  jsx: 'jsx',
  ts: 'typescript',
  mts: 'typescript',
  cts: 'typescript',
  tsx: 'tsx',
  json: 'json',
  jsonc: 'jsonc',
  html: 'html',
  htm: 'html',
  css: 'css',
  scss: 'scss',
  sass: 'sass',
  less: 'less',
  py: 'python',
  rb: 'ruby',
  rs: 'rust',
  go: 'go',
  java: 'java',
  kt: 'kotlin',
  kts: 'kotlin',
  swift: 'swift',
  c: 'c',
  h: 'c',
  cpp: 'cpp',
  cc: 'cpp',
  cxx: 'cpp',
  hpp: 'cpp',
  cs: 'csharp',
  php: 'php',
  sh: 'bash',
  bash: 'bash',
  zsh: 'bash',
  sql: 'sql',
  yaml: 'yaml',
  yml: 'yaml',
  toml: 'toml',
  xml: 'xml',
  xsl: 'xml',
  lua: 'lua',
  r: 'r',
  dart: 'dart',
  vue: 'vue',
  svelte: 'svelte',
  graphql: 'graphql',
  gql: 'graphql',
  dockerfile: 'dockerfile',
  makefile: 'makefile',
  zig: 'zig',
  elixir: 'elixir',
  ex: 'elixir',
  exs: 'elixir',
};

export function getFileType(name: string): FileType {
  const ext = name.split('.').pop()?.toLowerCase() ?? '';
  const baseName = name.toLowerCase();
  if (['md', 'mdx', 'markdown'].includes(ext)) return 'markdown';
  if (ext === 'pdf') return 'pdf';
  if (EXT_TO_LANG[ext]) return 'code';
  if (AUDIO_EXTS.includes(ext)) return 'audio';
  if (NATIVE_VIDEO_EXTS.includes(ext)) return 'video';
  if (IMAGE_EXTS.includes(ext)) return 'image';
  if (
    baseName.endsWith('.tar.gz') ||
    baseName.endsWith('.tar.bz2') ||
    baseName.endsWith('.tar.xz') ||
    baseName.endsWith('.tar.zst')
  )
    return 'archive';
  if (ARCHIVE_EXTS.includes(ext)) return 'archive';
  if (baseName === 'dockerfile' || baseName === 'makefile') return 'code';
  return 'text';
}

export function getLang(name: string): string {
  const ext = name.split('.').pop()?.toLowerCase() ?? '';
  const baseName = name.toLowerCase();
  if (baseName === 'dockerfile') return 'dockerfile';
  if (baseName === 'makefile') return 'makefile';
  return EXT_TO_LANG[ext] ?? 'text';
}

export function getExt(name: string): string {
  return name.split('.').pop()?.toLowerCase() ?? '';
}

export function formatTime(s: number): string {
  if (!isFinite(s) || isNaN(s)) return '0:00';
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = Math.floor(s % 60);
  if (h > 0) return `${h}:${m.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
  return `${m}:${sec.toString().padStart(2, '0')}`;
}

export function getRawUrl(filePath: string, root?: string, audioTrack?: number): string {
  const headers = getHeaders();
  const token = headers['Authorization']?.replace('Bearer ', '') ?? '';
  const rootParam = root && root !== 'home' ? `&root=${encodeURIComponent(root)}` : '';
  const audioParam = audioTrack && audioTrack > 0 ? `&audio=${audioTrack}` : '';
  return `${API_URL}/file-browser/raw?path=${encodeURIComponent(filePath)}&token=${encodeURIComponent(token)}${rootParam}${audioParam}`;
}

export function getAudioTracksUrl(filePath: string, root?: string): string {
  const headers = getHeaders();
  const token = headers['Authorization']?.replace('Bearer ', '') ?? '';
  const rootParam = root && root !== 'home' ? `&root=${encodeURIComponent(root)}` : '';
  return `${API_URL}/file-browser/audio-tracks?path=${encodeURIComponent(filePath)}&token=${encodeURIComponent(token)}${rootParam}`;
}

export function getSubtitlesUrl(filePath: string, root?: string): string {
  const headers = getHeaders();
  const token = headers['Authorization']?.replace('Bearer ', '') ?? '';
  const rootParam = root && root !== 'home' ? `&root=${encodeURIComponent(root)}` : '';
  return `${API_URL}/file-browser/subtitles?path=${encodeURIComponent(filePath)}&token=${encodeURIComponent(token)}${rootParam}`;
}

export function getSubtitleVttUrl(filePath: string, track: number, root?: string): string {
  const headers = getHeaders();
  const token = headers['Authorization']?.replace('Bearer ', '') ?? '';
  const rootParam = root && root !== 'home' ? `&root=${encodeURIComponent(root)}` : '';
  return `${API_URL}/file-browser/subtitle-vtt?path=${encodeURIComponent(filePath)}&track=${track}&token=${encodeURIComponent(token)}${rootParam}`;
}

export function getArchiveBaseName(name: string): string {
  const lower = name.toLowerCase();
  for (const compound of ['.tar.gz', '.tar.bz2', '.tar.xz', '.tar.zst']) {
    if (lower.endsWith(compound)) return name.slice(0, -compound.length);
  }
  const dotIdx = name.lastIndexOf('.');
  return dotIdx > 0 ? name.slice(0, dotIdx) : name;
}
