import { createRequire } from "module";

const require = createRequire(import.meta.url);
const pkg = require("../package.json");

export async function checkUpdate() {
  try {
    const res = await fetch(`https://registry.npmjs.org/${pkg.name}/latest`, {
      signal: AbortSignal.timeout(3000)
    });
    if (!res.ok) return null;
    const data = await res.json();
    const latest = data.version;
    if (latest && latest !== pkg.version && isNewer(latest, pkg.version)) {
      return { current: pkg.version, latest };
    }
  } catch {}
  return null;
}

function isNewer(latest, current) {
  const l = latest.split(".").map(Number);
  const c = current.split(".").map(Number);
  for (let i = 0; i < 3; i++) {
    if ((l[i] || 0) > (c[i] || 0)) return true;
    if ((l[i] || 0) < (c[i] || 0)) return false;
  }
  return false;
}
