import type { ModrinthProjectType, ModrinthVersion, SoftwareFamily } from './modrinth';

export function resolveModrinthLoader(
  softwareFamily: SoftwareFamily,
): string | null {
  switch (softwareFamily) {
    case 'PAPER':
    case 'PURPUR':
      return 'paper';
    case 'FABRIC':
      return 'fabric';
    case 'FORGE':
      return 'forge';
    case 'NEOFORGE':
      return 'neoforge';
    case 'QUILT':
      return 'quilt';
    default:
      return null;
  }
}

export function resolveProjectType(
  softwareFamily: SoftwareFamily,
): ModrinthProjectType | null {
  switch (softwareFamily) {
    case 'PAPER':
    case 'PURPUR':
      return 'plugin';
    case 'FABRIC':
    case 'FORGE':
    case 'NEOFORGE':
    case 'QUILT':
      return 'mod';
    default:
      return null;
  }
}

export function resolveInstallDirectory(projectType: ModrinthProjectType): string {
  switch (projectType) {
    case 'plugin':
      return 'plugins';
    case 'mod':
      return 'mods';
    case 'modpack':
      return 'modpacks';
    default:
      return 'datapacks';
  }
}

export function isVersionCompatible(
  version: ModrinthVersion,
  gameVersion: string,
  loader: string,
): boolean {
  const gameMatch = version.game_versions.some(
    (value) => value === gameVersion || gameVersion.startsWith(value),
  );
  const loaderMatch = version.loaders.includes(loader);
  return gameMatch && loaderMatch;
}

export function pickPrimaryFile(version: ModrinthVersion): ModrinthVersion['files'][number] | null {
  const jarFiles = version.files.filter((file) =>
    file.filename.toLowerCase().endsWith('.jar'),
  );

  if (jarFiles.length === 0) {
    return version.files[0] ?? null;
  }

  return jarFiles.find((file) => file.primary) ?? jarFiles[0] ?? null;
}
