import path from 'node:path';

/**
 * TFDS npm 版本比较与 registry 读取（四包共享）
 */

export function parseVersion(version) {
  return String(version || '')
    .trim()
    .replace(/^v/i, '')
    .split('-')[0]
    .split('.')
    .map((part) => Number.parseInt(part, 10) || 0);
}

export function compareVersions(a, b) {
  const av = parseVersion(a);
  const bv = parseVersion(b);
  const len = Math.max(av.length, bv.length, 3);
  for (let i = 0; i < len; i += 1) {
    const left = av[i] || 0;
    const right = bv[i] || 0;
    if (left > right) return 1;
    if (left < right) return -1;
  }
  return 0;
}

export function formatDateToMinute(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  const parts = new Intl.DateTimeFormat('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).formatToParts(date);
  const byType = Object.fromEntries(parts.map((part) => [part.type, part.value]));
  return `${byType.year}-${byType.month}-${byType.day} ${byType.hour}:${byType.minute}`;
}

/**
 * @param {string} packageName
 */
export async function fetchNpmPackageMetadata(packageName) {
  const registryUrl = `https://registry.npmjs.org/${encodeURIComponent(packageName).replace('%2F', '%2f')}`;
  const response = await fetch(registryUrl, { headers: { accept: 'application/json' } });
  if (!response.ok) {
    throw new Error(`npm registry 返回 ${response.status} ${response.statusText}`);
  }
  return response.json();
}

export function resolveProjectRoot(explicit) {
  return path.resolve(
    explicit || process.env.TFDS_PROJECT_ROOT || process.env.INIT_CWD || process.cwd(),
  );
}
