const argumentsList = process.argv.slice(2);
if (argumentsList[0] === "--") argumentsList.shift();
const [serviceUrl, expectedVersion = "", workerName = ""] = argumentsList;

function fail(message) {
  throw new Error(message);
}

if (!serviceUrl) {
  fail("Usage: node scripts/check-readiness.mjs <service-url> [expected-version-id] [worker-name]");
}
if (workerName && !expectedVersion) fail("A Worker override requires an expected version ID.");

const url = new URL("/ready", serviceUrl.endsWith("/") ? serviceUrl : `${serviceUrl}/`);
if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
  fail("Readiness checks require HTTPS except on localhost.");
}

const headers = { accept: "application/json" };
if (workerName) {
  headers["Cloudflare-Workers-Version-Overrides"] = `${workerName}="${expectedVersion}"`;
}

let result;
try {
  result = await fetch(url, { headers, signal: AbortSignal.timeout(15_000) });
} catch {
  fail("The readiness endpoint could not be reached.");
}

let body;
try { body = await result.json(); }
catch { fail("The readiness endpoint did not return JSON."); }

if (result.status !== 200 || body?.ok !== true || body?.ready !== true ||
    body?.service !== "smartcut64-licensing" || body?.schema !== 2 ||
    typeof body?.version_id !== "string" || !body.version_id) {
  fail(`Readiness failed (HTTP ${result.status}).`);
}
if (expectedVersion && body.version_id !== expectedVersion) {
  fail("The expected Worker version was not served.");
}

console.log(`SmartCut64 licensing is ready (version ${body.version_id}).`);
