import {
  isProjectProfile,
  projectModeById,
  projectModeForProfile,
  type ProjectModeDefinition,
} from '@learnitive/project-runtime';

function modeFromMetadata(metadata: Record<string, unknown> | undefined): ProjectModeDefinition | undefined {
  if (!metadata) return undefined;
  if (isProjectProfile(metadata.projectProfile)) {
    const mode = projectModeForProfile(metadata.projectProfile);
    if (mode) return mode;
  }
  return projectModeById(typeof metadata.projectModeId === 'string' ? metadata.projectModeId : undefined);
}

const MODE_FILE_NAMES: Readonly<Record<string, string>> = Object.freeze({
  latex: 'untitled.tex',
  html: 'untitled.html',
  javascript: 'untitled.js',
  typescript: 'untitled.ts',
  'node-javascript': 'untitled.js',
  'node-typescript': 'untitled.ts',
  python: 'untitled.py',
  c: 'untitled.c',
  cpp: 'untitled.cpp',
  java: 'Main.java',
  go: 'main.go',
  rust: 'main.rs',
  php: 'index.php',
  ruby: 'main.rb',
  r: 'main.R',
  shell: 'script.sh',
  markdown: 'untitled.md',
  'typescript-vite': 'untitled.ts',
  'react-vite-javascript': 'untitled.jsx',
  'react-vite-typescript': 'untitled.tsx',
  'vue-vite': 'untitled.vue',
  'svelte-vite': 'untitled.svelte',
});

/** Suggest a new source-file name without leaking LaTeX defaults into other project modes. */
export function suggestedProjectFileName(
  metadata: Record<string, unknown> | undefined,
  currentPath?: string,
): string {
  const mode = modeFromMetadata(metadata);
  const byMode = mode ? MODE_FILE_NAMES[mode.id] : undefined;
  if (byMode) return byMode;

  const leaf = String(currentPath || '').replaceAll('\\', '/').split('/').at(-1) || '';
  const match = leaf.match(/(\.[a-z0-9]+)$/iu);
  return match?.[1] ? `untitled${match[1].toLowerCase()}` : 'untitled.txt';
}
