import { readIfExists, updateCachePath, writeAtomic } from "@designpaca/core";

const DAY = 24 * 60 * 60 * 1000;
const REGISTRY = "https://registry.npmjs.org/designpaca/latest";

interface Cache {
  checkedAt: number;
  latest: string;
}

function isNewer(latest: string, current: string): boolean {
  const norm = (v: string) => v.split("-")[0]!.split(".").map((n) => Number.parseInt(n, 10) || 0);
  const [a, b] = [norm(latest), norm(current)];
  for (let i = 0; i < 3; i++) {
    const l = a[i] ?? 0;
    const c = b[i] ?? 0;
    if (l !== c) return l > c;
  }
  return false;
}

/**
 * 하루 한 번만 레지스트리를 본다. 네트워크가 없거나 느리면 조용히 포기한다 —
 * 업데이트 확인 때문에 CLI 가 멈추는 일은 없어야 한다.
 */
export async function checkForUpdate(current: string): Promise<string | null> {
  if (process.env["DESIGNPACA_NO_UPDATE_CHECK"] === "1") return null;

  const cachePath = updateCachePath();
  const raw = await readIfExists(cachePath);
  if (raw) {
    try {
      const c = JSON.parse(raw) as Cache;
      if (Date.now() - c.checkedAt < DAY) {
        return isNewer(c.latest, current) ? c.latest : null;
      }
    } catch {
      /* 캐시가 깨졌으면 새로 받는다 */
    }
  }

  try {
    const res = await fetch(REGISTRY, {
      headers: { accept: "application/vnd.npm.install-v1+json" },
      signal: AbortSignal.timeout(2500),
    });
    if (!res.ok) return null;
    const body = (await res.json()) as { version?: string };
    const latest = body.version;
    if (!latest) return null;
    await writeAtomic(cachePath, JSON.stringify({ checkedAt: Date.now(), latest } satisfies Cache));
    return isNewer(latest, current) ? latest : null;
  } catch {
    return null;
  }
}
