export const CODE_THEME = 'github-dark';

const SUPPORTED_LANGS = [
  'text',
  'plaintext',
  'bash',
  'shell',
  'sh',
  'zsh',
  'powershell',
  'c',
  'cpp',
  'go',
  'html',
  'java',
  'javascript',
  'typescript',
  'json',
  'markdown',
  'php',
  'python',
  'r',
  'ruby',
  'rust',
  'yaml',
] as const;

export type SupportedCodeBlockLanguage = (typeof SUPPORTED_LANGS)[number];

export const DEFAULT_CODE_BLOCK_LANGUAGE: SupportedCodeBlockLanguage = 'text';

export const CODE_BLOCK_LANGUAGE_OPTIONS = [
  { value: '', label: 'Text' },
  { value: 'bash', label: 'Bash' },
  { value: 'c', label: 'C' },
  { value: 'cpp', label: 'C++' },
  { value: 'go', label: 'Go' },
  { value: 'html', label: 'HTML' },
  { value: 'java', label: 'Java' },
  { value: 'javascript', label: 'JavaScript' },
  { value: 'json', label: 'JSON' },
  { value: 'markdown', label: 'Markdown' },
  { value: 'php', label: 'PHP' },
  { value: 'powershell', label: 'PowerShell' },
  { value: 'python', label: 'Python' },
  { value: 'r', label: 'R' },
  { value: 'ruby', label: 'Ruby' },
  { value: 'rust', label: 'Rust' },
  { value: 'shell', label: 'Shell' },
  { value: 'typescript', label: 'TypeScript' },
  { value: 'yaml', label: 'YAML' },
] as const;

const RUNNABLE_LANGUAGE_ALIASES: Record<string, string> = {
  bash: 'shell',
  c: 'c',
  cpp: 'cpp',
  'c++': 'cpp',
  go: 'go',
  java: 'java',
  javascript: 'javascript',
  js: 'javascript',
  php: 'php',
  py: 'python',
  python: 'python',
  r: 'r',
  ruby: 'ruby',
  rust: 'rust',
  sh: 'shell',
  shell: 'shell',
  ts: 'typescript',
  typescript: 'typescript',
};

export function getRawCodeBlockLanguage(language: unknown): string {
  if (typeof language !== 'string') {
    return '';
  }
  return language.trim().toLowerCase();
}

export function runnableCodeBlockLanguage(language: unknown): string | undefined {
  return RUNNABLE_LANGUAGE_ALIASES[getRawCodeBlockLanguage(language)];
}

export function normalizeCodeBlockLanguage(
  language: unknown,
): SupportedCodeBlockLanguage {
  const normalized = getRawCodeBlockLanguage(language);
  if (!normalized) {
    return DEFAULT_CODE_BLOCK_LANGUAGE;
  }

  if (normalized === 'ps1' || normalized === 'pwsh') {
    return 'powershell';
  }
  if (normalized === 'js') {
    return 'javascript';
  }
  if (normalized === 'ts') {
    return 'typescript';
  }
  if (normalized === 'yml') {
    return 'yaml';
  }
  if (normalized === 'console') {
    return 'bash';
  }

  if ((SUPPORTED_LANGS as readonly string[]).includes(normalized)) {
    return normalized as SupportedCodeBlockLanguage;
  }

  return DEFAULT_CODE_BLOCK_LANGUAGE;
}
