const encoder = new TextEncoder();
const maximumRequestBytes = 16 * 1024;
const maximumWebhookBytes = 128 * 1024;
const signingReadinessChallenge = encoder.encode("SmartCut64 licensing signing readiness v1");
const licenseStateMarkerKey = "system:namespace-marker:v1";
const signingKeyCache = new WeakMap();
const activationLocks = new Map();
const defaultTrustedPublicModulusSha256ByProduct = Object.freeze({
  // These public fingerprints bind each deployed Lemon product to the key
  // compiled into its corresponding SmartCut64 build. Changing a secret and
  // a Wrangler variable together therefore cannot make a wrong key look ready.
  "1278355": "edac4dccb2b5e246bc828df7aafba9b69dcb1d5f341ba597e11131c53f274d9d",
  "1304562": "6a1684cc402c989015d31d17584d0b9d89783e81774886e0bcce9893e335026f"
});
const defaultTrustedCommerceByProduct = Object.freeze({
  "1278355": Object.freeze({
    apiBase: "https://api.lemonsqueezy.com/v1/licenses",
    store: "448537",
    variants: Object.freeze(["1998551"]),
    licenseStateMarker: "smartcut64-license-state:test:24c50e674aed45f9830034c9451706e3:v1"
  }),
  "1304562": Object.freeze({
    apiBase: "https://api.lemonsqueezy.com/v1/licenses",
    store: "448537",
    variants: Object.freeze(["2040403"]),
    licenseStateMarker: "smartcut64-license-state:production:b48acd15f08540abbdb7026cbdbb0319:v1"
  })
});
const jsonHeaders = {
  "content-type": "application/json; charset=utf-8",
  "cache-control": "no-store",
  "x-content-type-options": "nosniff"
};

function response(status, body) {
  return new Response(JSON.stringify(body), { status, headers: jsonHeaders });
}

function failure(status, code, message) {
  return response(status, { ok: false, code, message });
}

async function readLimitedText(request, maximumBytes) {
  const declared = Number(request.headers.get("content-length") || "0");
  if (Number.isFinite(declared) && declared > maximumBytes) throw new Error("request_too_large");
  const bytes = new Uint8Array(await request.arrayBuffer());
  if (bytes.byteLength > maximumBytes) throw new Error("request_too_large");
  try {
    return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
  } catch {
    throw new Error("invalid_encoding");
  }
}

async function readJson(request) {
  const text = await readLimitedText(request, maximumRequestBytes);
  const value = JSON.parse(text);
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("invalid_json");
  return value;
}

function validInstallationId(value) {
  return typeof value === "string" && /^[0-9a-f]{32}$/i.test(value);
}

function validEmail(value) {
  return typeof value === "string" && value.length >= 3 && value.length <= 254 &&
         /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}

function validLicenseKey(value) {
  return typeof value === "string" && value.length >= 8 && value.length <= 256 &&
         !/[\x00-\x20\x7f]/.test(value);
}

function safeClaim(value, maximum) {
  return String(value || "SmartCut64 customer")
    .replace(/[\x00-\x1f\x7f]/g, " ")
    .replace(/\s+/g, " ")
    .trim()
    .slice(0, maximum) || "SmartCut64 customer";
}

function base64Url(bytes) {
  let binary = "";
  for (let offset = 0; offset < bytes.length; offset += 0x8000) {
    binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
  }
  return btoa(binary).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
}

function pemBytes(pem) {
  const encoded = String(pem || "")
    .replace(/-----BEGIN PRIVATE KEY-----/g, "")
    .replace(/-----END PRIVATE KEY-----/g, "")
    .replace(/\s/g, "");
  if (!encoded) throw new Error("missing_signing_key");
  const binary = atob(encoded);
  return Uint8Array.from(binary, character => character.charCodeAt(0));
}

async function importSigningKey(pem) {
  return crypto.subtle.importKey(
    "pkcs8",
    pemBytes(pem),
    { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
    false,
    ["sign"]
  );
}

function publicModulusBytes(value) {
  const modulus = String(value || "").trim();
  if (!/^(?:[0-9a-f]{2}){256,512}$/i.test(modulus)) throw new Error("invalid_public_key");
  const bytes = Uint8Array.from(modulus.match(/../g), byte => Number.parseInt(byte, 16));
  if (bytes[0] === 0) throw new Error("invalid_public_key");
  return bytes;
}

async function importVerificationKey(modulusHex) {
  return crypto.subtle.importKey(
    "jwk",
    {
      kty: "RSA",
      n: base64Url(publicModulusBytes(modulusHex)),
      e: "AQAB",
      alg: "RS256",
      ext: true,
      key_ops: ["verify"]
    },
    { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
    false,
    ["verify"]
  );
}

async function validatedSigningKey(env, trustedFingerprints, trustedCommerceByProduct) {
  const privatePem = String(env?.SMARTCUT_PRIVATE_KEY_PEM || "");
  const publicModulus = String(env?.SMARTCUT_LICENSE_PUBLIC_MODULUS_HEX || "").trim().toLowerCase();
  const productId = String(env?.LEMON_PRODUCT_ID || "");
  const commerceSignature = [
    String(env?.LEMON_LICENSE_API_BASE || ""),
    String(env?.LEMON_STORE_ID || ""),
    String(env?.LEMON_VARIANT_IDS || "")
  ].join("|");
  const trustedFingerprint = trustedFingerprints?.[productId];
  const trustedCommerce = trustedCommerceByProduct?.[productId];
  const trustedCommerceSignature = trustedCommerce
    ? `${String(trustedCommerce.apiBase || "")}|${String(trustedCommerce.store || "")}|${(trustedCommerce.variants || []).join(",")}|${String(trustedCommerce.licenseStateMarker || "")}`
    : "";
  const cached = signingKeyCache.get(env);
  if (cached?.privatePem === privatePem && cached?.publicModulus === publicModulus &&
      cached?.productId === productId && cached?.commerceSignature === commerceSignature &&
      cached?.trustedFingerprint === trustedFingerprint &&
      cached?.trustedCommerceSignature === trustedCommerceSignature)
    return cached.keyPromise;

  // Cache the in-flight promise, including a fail-closed rejection. Concurrent
  // requests in the same isolate must not repeat expensive RSA work.
  const keyPromise = (async () => {
    const modulusBytes = publicModulusBytes(publicModulus);
    if (typeof trustedFingerprint !== "string" || !/^[0-9a-f]{64}$/i.test(trustedFingerprint))
      throw new Error("untrusted_product");
    if (!trustedCommerce || typeof trustedCommerce.store !== "string" ||
        typeof trustedCommerce.apiBase !== "string" || !Array.isArray(trustedCommerce.variants) ||
        trustedCommerce.variants.length === 0 ||
        !/^smartcut64-license-state:(?:test|production):[0-9a-f]{32}:v1$/.test(
          String(trustedCommerce.licenseStateMarker || ""))) throw new Error("untrusted_product");
    const ids = configuredIds(env);
    const apiBase = String(env?.LEMON_LICENSE_API_BASE || "").replace(/\/$/, "");
    if (apiBase !== trustedCommerce.apiBase || ids.store !== trustedCommerce.store ||
        ids.variants.size !== trustedCommerce.variants.length ||
        trustedCommerce.variants.some(variant => !ids.variants.has(variant))) {
      throw new Error("untrusted_commerce_configuration");
    }
    const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", modulusBytes));
    const fingerprint = Array.from(digest, byte => byte.toString(16).padStart(2, "0")).join("");
    if (fingerprint !== trustedFingerprint.toLowerCase()) throw new Error("untrusted_public_key");

    const [privateKey, publicKey] = await Promise.all([
      importSigningKey(privatePem),
      importVerificationKey(publicModulus)
    ]);
    const signature = await crypto.subtle.sign(
      "RSASSA-PKCS1-v1_5", privateKey, signingReadinessChallenge);
    if (!await crypto.subtle.verify(
      "RSASSA-PKCS1-v1_5", publicKey, signature, signingReadinessChallenge)) {
      throw new Error("signing_key_mismatch");
    }
    return privateKey;
  })();
  signingKeyCache.set(env, {
    privatePem, publicModulus, productId, commerceSignature, trustedFingerprint,
    trustedCommerceSignature, keyPromise
  });
  return keyPromise;
}

async function licenseStateBindingReady(env, trustedCommerceByProduct) {
  const expected = trustedCommerceByProduct?.[String(env?.LEMON_PRODUCT_ID || "")]
    ?.licenseStateMarker;
  if (typeof expected !== "string" || !env?.LICENSE_STATE?.get) return false;
  try {
    return await env.LICENSE_STATE.get(licenseStateMarkerKey) === expected;
  } catch {
    return false;
  }
}

async function sha256Hex(value) {
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
  return Array.from(digest, byte => byte.toString(16).padStart(2, "0")).join("");
}

async function activationRateFailure(request, env, keyHash) {
  const actor = request.headers.get("cf-connecting-ip") || "unknown";
  const checks = [
    [env.LICENSE_RATE_LIMIT, `license:${keyHash}`],
    [env.ACTOR_RATE_LIMIT, `actor:${actor}`]
  ];
  try {
    for (const [limiter, key] of checks) {
      if (!limiter?.limit) {
        return failure(503, "rate_limit_unavailable", "Licence activation is temporarily unavailable.");
      }
      const { success } = await limiter.limit({ key });
      if (!success) {
        return failure(429, "rate_limited",
          "Too many licence requests were received. Wait one minute and try again.");
      }
    }
  } catch {
    return failure(503, "rate_limit_unavailable", "Licence activation is temporarily unavailable.");
  }
  return null;
}

function configuredIds(env) {
  return {
    store: String(env.LEMON_STORE_ID || ""),
    product: String(env.LEMON_PRODUCT_ID || ""),
    variants: new Set(String(env.LEMON_VARIANT_IDS || "").split(",").map(value => value.trim()).filter(Boolean))
  };
}

function validHttpsUrl(value) {
  try { return new URL(String(value || "")).protocol === "https:"; }
  catch { return false; }
}

function activationConfigured(env) {
  const ids = configuredIds(env);
  return Boolean(
    env?.LICENSE_STATE?.get && env.LICENSE_STATE?.put &&
    env?.SMARTCUT_PRIVATE_KEY_PEM && env?.SMARTCUT_LICENSE_PUBLIC_MODULUS_HEX &&
    ids.store && ids.product && ids.variants.size > 0 &&
    validHttpsUrl(env.LEMON_LICENSE_API_BASE || "https://api.lemonsqueezy.com/v1/licenses")
  );
}

function serviceConfigured(env) {
  return activationConfigured(env) && Boolean(
    env?.LICENSE_RATE_LIMIT?.limit && env?.ACTOR_RATE_LIMIT?.limit &&
    env?.LEMON_WEBHOOK_SECRET && env?.CF_VERSION_METADATA?.id);
}

function verifiedMeta(meta, email, env) {
  const ids = configuredIds(env);
  if (!ids.store || !ids.product || ids.variants.size === 0) return false;
  return String(meta?.store_id ?? "") === ids.store &&
         String(meta?.product_id ?? "") === ids.product &&
         ids.variants.has(String(meta?.variant_id ?? "")) &&
         String(meta?.customer_email || "").trim().toLowerCase() === email;
}

function numericLemonId(value) {
  if (Number.isSafeInteger(value) && value > 0) return String(value);
  if (typeof value === "string" && /^[1-9][0-9]{0,18}$/.test(value)) return value;
  return null;
}

function validLemonInstanceId(value) {
  return typeof value === "string" &&
    /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
}

function lemonIdentity(payload) {
  const licenseId = numericLemonId(payload?.license_key?.id);
  const orderId = numericLemonId(payload?.meta?.order_id);
  return licenseId && orderId ? { licenseId, orderId } : null;
}

async function lemonRequest(fetchImpl, env, operation, fields) {
  const base = String(env.LEMON_LICENSE_API_BASE || "https://api.lemonsqueezy.com/v1/licenses").replace(/\/$/, "");
  const body = new URLSearchParams(fields);
  let result;
  try {
    result = await fetchImpl(`${base}/${operation}`, {
      method: "POST",
      headers: {
        accept: "application/json",
        "content-type": "application/x-www-form-urlencoded"
      },
      body
    });
  } catch {
    const error = new Error("lemon_unavailable");
    error.origin = "lemon";
    error.status = 0;
    throw error;
  }
  const payload = await result.json().catch(() => null);
  if (!result.ok || !payload) {
    const error = new Error("lemon_unavailable");
    error.origin = "lemon";
    error.status = result.status;
    error.upstreamMessage = typeof payload?.error === "string" ? payload.error.slice(0, 512) : "";
    throw error;
  }
  return payload;
}

async function issueEntitlement(signingKey, record) {
  const issued = Math.floor(Date.now() / 1000);
  // Personal purchases are genuine perpetual licences. The machine binding and
  // Lemon activation limit still apply, but clean export does not depend on a
  // periodically renewed service token after activation.
  const expires = 0;
  const payload = [
    "product=SmartCut64",
    "edition=paid",
    `license_id=${safeClaim(`lemon-${record.license_id}`, 128)}`,
    `customer=${safeClaim(record.customer_name || record.customer_email, 512)}`,
    `installation_id=${record.installation_id}`,
    `issued_unix=${issued}`,
    `not_before_unix=${issued - 300}`,
    `expires_unix=${expires}`,
    "clean_export=1"
  ].join("\n");
  const payloadSegment = base64Url(encoder.encode(payload));
  const signedText = `SC64-1.${payloadSegment}`;
  const signature = new Uint8Array(await crypto.subtle.sign(
    "RSASSA-PKCS1-v1_5", signingKey, encoder.encode(signedText)));
  return {
    token: `${signedText}.${base64Url(signature)}`,
    expires_unix: expires,
    license_id: `lemon-${record.license_id}`
  };
}

async function indexRecord(kv, indexKey, recordKey) {
  await kv.put(`index:${indexKey}:${recordKey}`, recordKey);
}

async function indexedRecordKeys(kv, indexKey) {
  const records = new Set();
  const legacy = await kv.get(indexKey, "json");
  if (Array.isArray(legacy)) {
    for (const value of legacy) if (typeof value === "string") records.add(value);
  }
  if (!kv.list) return [...records];
  const prefix = `index:${indexKey}:`;
  let cursor;
  do {
    const page = await kv.list({ prefix, cursor });
    for (const key of page?.keys || []) {
      const value = await kv.get(key.name);
      if (typeof value === "string" && value) records.add(value);
    }
    cursor = page?.list_complete === false ? page.cursor : undefined;
  } while (cursor);
  return [...records];
}

async function recordRevocation(kv, record) {
  for (const key of [`revocation:license:${record.license_id}`, `revocation:order:${record.order_id}`]) {
    const marker = await kv.get(key, "json");
    if (marker?.reason) return marker.reason;
  }
  return null;
}

function recoveryStatus(record) {
  const explicit = record?.recovery_status;
  if (explicit !== undefined) {
    return ["activation_pending", "rollback_pending"].includes(explicit)
      ? explicit : "invalid";
  }
  return ["activation_pending", "rollback_pending"].includes(record?.status)
    ? record.status : "";
}

function setStableStatus(record, status) {
  record.status = status;
  delete record.recovery_status;
}

function setRecoveryStatus(record, status) {
  // The deployed v1 Worker blocks status=revoked without calling Lemon. The
  // new Worker dispatches recovery_status first, making pending state safe if
  // production must roll back to v1 after candidate traffic.
  record.status = "revoked";
  record.recovery_status = status;
}

async function markRecordRevoked(kv, recordKey, record, reason) {
  setStableStatus(record, "revoked");
  record.revocation_reason = reason;
  record.updated_at = new Date().toISOString();
  await kv.put(recordKey, JSON.stringify(record));
}

async function saveRecord(kv, recordKey, record) {
  // Publish active state last, replacing the guarded pre-activation intent. A
  // failed index write can leave only a harmless dangling index, never an
  // apparently active installation whose Lemon seat was rolled back.
  await indexRecord(kv, `license:${record.license_id}`, recordKey);
  await indexRecord(kv, `order:${record.order_id}`, recordKey);
  await kv.put(recordKey, JSON.stringify(record));
}

async function rememberRollbackPending(kv, recordKey, record, reason) {
  setRecoveryStatus(record, "rollback_pending");
  record.rollback_reason = reason;
  record.updated_at = new Date().toISOString();
  try { await saveRecord(kv, recordKey, record); }
  catch {
    // The primary record is the minimum recovery handle. Indexes can be
    // rebuilt idempotently on a later successful write.
    try { await kv.put(recordKey, JSON.stringify(record)); }
    catch { return false; }
  }
  return true;
}

function deactivationComplete(result, record, env) {
  if (result?.deactivated === true) {
    const identity = lemonIdentity(result);
    return verifiedMeta(result.meta, record.customer_email, env) && Boolean(identity) &&
      identity.licenseId === record.license_id && identity.orderId === record.order_id;
  }
  return result?.deactivated === false &&
    /already deactivated|instance.*not found|instance.*does not exist/i
      .test(String(result?.error || ""));
}

function deactivationAlreadyGone(error) {
  return error?.origin === "lemon" &&
    /already deactivated|instance.*not found|instance.*does not exist/i
      .test(String(error?.upstreamMessage || ""));
}

async function withActivationLock(recordKey, operation) {
  const previous = activationLocks.get(recordKey) || Promise.resolve();
  let release;
  const current = new Promise(resolve => { release = resolve; });
  activationLocks.set(recordKey, current);
  await previous;
  try {
    return await operation();
  } finally {
    release();
    if (activationLocks.get(recordKey) === current) activationLocks.delete(recordKey);
  }
}

async function retireRecordedInstance(fetchImpl, env, licenseKey, recordKey, record) {
  try {
    const result = await lemonRequest(fetchImpl, env, "deactivate", {
      license_key: licenseKey,
      instance_id: record.instance_id
    });
    if (!deactivationComplete(result, record, env)) return false;
  } catch (error) {
    if (!deactivationAlreadyGone(error)) return false;
  }
  setStableStatus(record, "deactivated");
  record.updated_at = new Date().toISOString();
  try {
    await env.LICENSE_STATE.put(recordKey, JSON.stringify(record));
    return true;
  } catch {
    return false;
  }
}

async function clearActivationIntent(env, recordKey, record) {
  setStableStatus(record, "deactivated");
  record.updated_at = new Date().toISOString();
  try {
    await env.LICENSE_STATE.put(recordKey, JSON.stringify(record));
    return true;
  } catch {
    return false;
  }
}

async function compensateActivation(fetchImpl, env, licenseKey, recordKey, record, reason) {
  try {
    const result = await lemonRequest(fetchImpl, env, "deactivate", {
      license_key: licenseKey,
      instance_id: record.instance_id
    });
    if (deactivationComplete(result, record, env)) {
      setStableStatus(record, "deactivated");
      record.updated_at = new Date().toISOString();
      try { await env.LICENSE_STATE.put(recordKey, JSON.stringify(record)); }
      catch {}
      return true;
    }
  } catch {}
  await rememberRollbackPending(env.LICENSE_STATE, recordKey, record, reason);
  return false;
}

async function reconcileRollback(fetchImpl, env, licenseKey, email, recordKey, record) {
  if (!validLemonInstanceId(record.instance_id) || !numericLemonId(record.license_id) ||
      !numericLemonId(record.order_id)) return false;
  try {
    const validation = await lemonRequest(fetchImpl, env, "validate", {
      license_key: licenseKey,
      instance_id: record.instance_id
    });
    if (validation.valid === true) {
      const identity = lemonIdentity(validation);
      if (!verifiedMeta(validation.meta, email, env) || !identity ||
          identity.licenseId !== record.license_id || identity.orderId !== record.order_id) return false;
    }
    return retireRecordedInstance(fetchImpl, env, licenseKey, recordKey, record);
  } catch (error) {
    if (deactivationAlreadyGone(error)) {
      setStableStatus(record, "deactivated");
      record.updated_at = new Date().toISOString();
      try {
        await env.LICENSE_STATE.put(recordKey, JSON.stringify(record));
        return true;
      } catch {}
    }
    return false;
  }
}

async function activate(request, env, fetchImpl, trustedFingerprints, trustedCommerceByProduct) {
  let body;
  try { body = await readJson(request); }
  catch (error) {
    return failure(error.message === "request_too_large" ? 413 : 400,
                   error.message === "request_too_large" ? "request_too_large" : "invalid_request",
                   "The activation request is invalid.");
  }
  const licenseKey = String(body.license_key || "").trim();
  const email = String(body.email || "").trim().toLowerCase();
  const installationId = String(body.installation_id || "").trim().toLowerCase();
  if (!validLicenseKey(licenseKey) || !validEmail(email) || !validInstallationId(installationId)) {
    return failure(400, "invalid_fields", "Enter the purchase email, licence key and installation ID.");
  }
  if (!serviceConfigured(env)) {
    return failure(503, "service_not_configured", "Licence activation is temporarily unavailable.");
  }
  const keyHash = await sha256Hex(licenseKey);
  const rateFailure = await activationRateFailure(request, env, keyHash);
  if (rateFailure) return rateFailure;
  let signingKey;
  try { signingKey = await validatedSigningKey(env, trustedFingerprints, trustedCommerceByProduct); }
  catch { return failure(503, "service_not_configured", "Licence activation is temporarily unavailable."); }
  if (!await licenseStateBindingReady(env, trustedCommerceByProduct)) {
    return failure(503, "service_not_configured", "Licence activation is temporarily unavailable.");
  }
  const recordKey = `activation:${keyHash}:${installationId}`;
  return withActivationLock(recordKey, async () => {
    try {
    let record = await env.LICENSE_STATE.get(recordKey, "json");
    const existingRevocation = record ? await recordRevocation(env.LICENSE_STATE, record) : null;
    if (record && existingRevocation) {
      await markRecordRevoked(env.LICENSE_STATE, recordKey, record, existingRevocation);
      return failure(403, "licence_revoked", "The licence is no longer valid for this installation.");
    }
    const recovery = recoveryStatus(record);
    if (record && (recovery === "invalid" ||
        (recovery && !["revoked", recovery].includes(record.status)) ||
        (!recovery && !["active", "deactivated", "revoked"].includes(record.status)))) {
      return failure(503, "activation_state_invalid", "Licence activation state is unavailable.");
    }
    if (record && recovery === "activation_pending") {
      // The request may have reached Lemon after this durable intent was
      // written, but before an instance UUID was received or committed. With
      // no idempotency key or UUID, retrying activate could consume another
      // seat. Fail closed for privacy-safe operational reconciliation.
      return failure(503, "activation_recovery_pending",
        "A previous activation is still being recovered. Please contact support.");
    }
    if (record && recovery === "rollback_pending") {
      if (!await reconcileRollback(fetchImpl, env, licenseKey, email, recordKey, record)) {
        return failure(503, "activation_recovery_pending",
          "A previous activation is still being recovered. Please try again shortly.");
      }
      record = null;
    }
    if (record && record.status === "revoked") {
      return failure(403, "licence_revoked", "The licence is no longer valid for this installation.");
    }
    if (record && record.status === "active") {
      if (!validLemonInstanceId(record.instance_id) || !numericLemonId(record.license_id) ||
          !numericLemonId(record.order_id)) {
        return failure(503, "activation_state_invalid", "Licence activation state is unavailable.");
      }
      let validation;
      try {
        validation = await lemonRequest(fetchImpl, env, "validate", {
          license_key: licenseKey,
          instance_id: record.instance_id
        });
      } catch (error) {
        if (!deactivationAlreadyGone(error)) throw error;
        validation = { valid: false };
      }
      if (validation.valid !== true) {
        // A false instance result can mean manual deactivation, a disabled
        // licence or a transient Lemon inconsistency. First prove that the
        // key itself is still valid and belongs to this purchase, then retire
        // the recorded UUID before any replacement activation is allowed.
        const keyValidation = await lemonRequest(fetchImpl, env, "validate", {
          license_key: licenseKey
        });
        const identity = lemonIdentity(keyValidation);
        if (keyValidation.valid !== true) {
          return failure(403, "licence_not_valid",
            "The purchase could not be verified for SmartCut64.");
        }
        if (!verifiedMeta(keyValidation.meta, email, env) || !identity ||
            identity.licenseId !== record.license_id || identity.orderId !== record.order_id) {
          return failure(403, "purchase_mismatch",
            "The purchase details do not match this activation.");
        }
        if (!await retireRecordedInstance(fetchImpl, env, licenseKey, recordKey, record)) {
          return failure(503, "activation_recovery_pending",
            "A previous activation is still being recovered. Please try again shortly.");
        }
        record = null;
      } else if (!verifiedMeta(validation.meta, email, env)) {
        return failure(403, "purchase_mismatch", "The purchase email or SmartCut64 product details do not match.");
      } else {
        const identity = lemonIdentity(validation);
        if (!identity || identity.licenseId !== record.license_id || identity.orderId !== record.order_id) {
          return failure(403, "purchase_mismatch", "The purchase details do not match this activation.");
        }
      }
    }
    if (!record || record.status !== "active") {
      // Lemon validation without an instance ID is non-mutating. Verify the
      // purchase and prepare a valid entitlement before consuming a seat.
      const validation = await lemonRequest(fetchImpl, env, "validate", {
        license_key: licenseKey
      });
      const identity = lemonIdentity(validation);
      if (validation.valid !== true || !verifiedMeta(validation.meta, email, env) || !identity) {
        return failure(403, "licence_not_valid", "The purchase could not be verified for SmartCut64.");
      }
      record = {
        schema: "smartcut64-lemon-activation-v1",
        status: "revoked",
        recovery_status: "activation_pending",
        installation_id: installationId,
        instance_id: "",
        license_id: identity.licenseId,
        order_id: identity.orderId,
        customer_email: email,
        customer_name: safeClaim(validation.meta?.customer_name || email, 512),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      const revocation = await recordRevocation(env.LICENSE_STATE, record);
      if (revocation) {
        return failure(403, "licence_revoked", "The licence is no longer valid for this installation.");
      }
      const entitlement = await issueEntitlement(signingKey, record);

      // Persist an intent before asking Lemon to consume a seat. If an
      // activation response is lost, or rollback and later KV writes both
      // fail, this record prevents an identical retry from consuming another
      // activation without an operator reconciling the unknown outcome.
      try {
        await env.LICENSE_STATE.put(recordKey, JSON.stringify(record));
      } catch {
        return failure(503, "activation_commit_failed",
          "Licence activation could not be saved. Please try again.");
      }

      let activation;
      try {
        activation = await lemonRequest(fetchImpl, env, "activate", {
          license_key: licenseKey,
          instance_name: `SmartCut64 ${installationId}`
        });
      } catch (error) {
        // A 4xx is a definitive rejection, so it cannot have consumed a seat.
        // Network/5xx outcomes remain ambiguous and retain activation_pending.
        if (error?.origin === "lemon" && error?.status >= 400 && error?.status < 500 &&
            !await clearActivationIntent(env, recordKey, record)) {
          return failure(503, "activation_recovery_pending",
            "A previous activation is still being recovered. Please contact support.");
        }
        throw error;
      }
      const activatedIdentity = lemonIdentity(activation);
      if (activation.activated !== true || !validLemonInstanceId(activation.instance?.id) ||
          !verifiedMeta(activation.meta, email, env) ||
          !activatedIdentity || activatedIdentity.licenseId !== record.license_id ||
          activatedIdentity.orderId !== record.order_id) {
        if (activation.activated === false) {
          if (!await clearActivationIntent(env, recordKey, record)) {
            return failure(503, "activation_recovery_pending",
              "A previous activation is still being recovered. Please contact support.");
          }
          return failure(403, "licence_not_valid",
            "The purchase could not be verified for SmartCut64.");
        }
        if (activation.activated === true && validLemonInstanceId(activation.instance?.id)) {
          record.instance_id = String(activation.instance.id);
          if (!await compensateActivation(fetchImpl, env, licenseKey, recordKey, record,
            "activation_response_mismatch")) {
            return failure(503, "activation_recovery_pending",
              "A previous activation is still being recovered. Please try again shortly.");
          }
        } else {
          return failure(503, "activation_recovery_pending",
            "A previous activation is still being recovered. Please contact support.");
        }
        return failure(403, "licence_not_valid", "The purchase could not be verified for SmartCut64.");
      }
      record.instance_id = String(activation.instance.id);
      setStableStatus(record, "active");
      try {
        await saveRecord(env.LICENSE_STATE, recordKey, record);
      } catch {
        if (!await compensateActivation(fetchImpl, env, licenseKey, recordKey, record,
          "activation_commit_failed")) {
          return failure(503, "activation_recovery_pending",
            "A previous activation is still being recovered. Please try again shortly.");
        }
        return failure(503, "activation_commit_failed",
          "Licence activation could not be saved. Please try again.");
      }
      return response(200, {
        ok: true,
        entitlement: entitlement.token,
        expires_unix: entitlement.expires_unix,
        license_id: entitlement.license_id
      });
    }
    const revocation = await recordRevocation(env.LICENSE_STATE, record);
    if (revocation) {
      await markRecordRevoked(env.LICENSE_STATE, recordKey, record, revocation);
      return failure(403, "licence_revoked", "The licence is no longer valid for this installation.");
    }
    let entitlement;
    try {
      entitlement = await issueEntitlement(signingKey, record);
    } catch {
      return failure(503, "service_not_configured", "Licence activation is temporarily unavailable.");
    }
    return response(200, {
      ok: true,
      entitlement: entitlement.token,
      expires_unix: entitlement.expires_unix,
      license_id: entitlement.license_id
    });
    } catch (error) {
      if (error?.origin === "lemon" && error?.status === 429) {
        return failure(503, "upstream_rate_limited",
          "The purchase service is busy. Please wait one minute and try again.");
      }
      if (error?.origin === "lemon" && error?.status >= 400 && error?.status < 500) {
        if (/activation limit/i.test(String(error.upstreamMessage || ""))) {
          return failure(409, "activation_limit_reached",
            "This licence is already active on the maximum number of computers. Deactivate another computer before trying again.");
        }
        return failure(403, "licence_not_valid",
          "The licence key or purchase details could not be verified.");
      }
      if (error?.origin === "lemon")
        return failure(503, "upstream_unavailable", "The purchase service could not be reached. Please try again.");
      return failure(503, "activation_unavailable", "Licence activation is temporarily unavailable. Please try again.");
    }
  });
}

async function readiness(env, trustedFingerprints, trustedCommerceByProduct) {
  const versionId = typeof env?.CF_VERSION_METADATA?.id === "string"
    ? env.CF_VERSION_METADATA.id : null;
  const notReady = () => response(503, {
    ok: false,
    ready: false,
    code: "service_not_ready",
    message: "Licence service is not ready.",
    service: "smartcut64-licensing",
    schema: 2,
    version_id: versionId
  });
  if (!serviceConfigured(env)) return notReady();
  try { await validatedSigningKey(env, trustedFingerprints, trustedCommerceByProduct); }
  catch { return notReady(); }
  if (!await licenseStateBindingReady(env, trustedCommerceByProduct)) return notReady();
  return response(200, {
    ok: true,
    ready: true,
    service: "smartcut64-licensing",
    schema: 2,
    version_id: versionId
  });
}

async function deactivate(request, env, fetchImpl) {
  let body;
  try { body = await readJson(request); }
  catch (error) { return failure(400, "invalid_request", "The deactivation request is invalid."); }
  const licenseKey = String(body.license_key || "").trim();
  const installationId = String(body.installation_id || "").trim().toLowerCase();
  if (!validLicenseKey(licenseKey) || !validInstallationId(installationId)) {
    return failure(400, "invalid_fields", "The licence key and installation ID are required.");
  }
  if (!env.LICENSE_STATE) return failure(503, "service_not_configured", "Licence deactivation is unavailable.");
  const keyHash = await sha256Hex(licenseKey);
  const rateFailure = await activationRateFailure(request, env, keyHash);
  if (rateFailure) return rateFailure;
  const recordKey = `activation:${keyHash}:${installationId}`;
  const record = await env.LICENSE_STATE.get(recordKey, "json");
  if (!record || record.status !== "active" || recoveryStatus(record))
    return failure(404, "activation_not_found", "No active installation was found.");
  if (!validLemonInstanceId(record.instance_id))
    return failure(503, "activation_state_invalid", "Licence activation state is unavailable.");
  try {
    const result = await lemonRequest(fetchImpl, env, "deactivate", {
      license_key: licenseKey,
      instance_id: record.instance_id
    });
    if (!deactivationComplete(result, record, env))
      return failure(409, "deactivation_rejected", "The installation could not be deactivated.");
    setStableStatus(record, "deactivated");
    record.updated_at = new Date().toISOString();
    await env.LICENSE_STATE.put(recordKey, JSON.stringify(record));
    return response(200, { ok: true });
  } catch (error) {
    if (error?.status >= 400 && error?.status < 500) {
      return failure(409, "deactivation_rejected", "The installation could not be deactivated.");
    }
    return failure(503, "upstream_unavailable", "The purchase service could not be reached. Please try again.");
  }
}

function hexBytes(value) {
  if (typeof value !== "string" || !/^[0-9a-f]{64}$/i.test(value)) return null;
  return Uint8Array.from(value.match(/../g), byte => Number.parseInt(byte, 16));
}

function equalBytes(left, right) {
  if (!left || !right || left.length !== right.length) return false;
  let difference = 0;
  for (let index = 0; index < left.length; ++index) difference |= left[index] ^ right[index];
  return difference === 0;
}

async function validWebhookSignature(bytes, signature, secret) {
  if (!secret) return false;
  const key = await crypto.subtle.importKey("raw", encoder.encode(secret),
    { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const expected = new Uint8Array(await crypto.subtle.sign("HMAC", key, bytes));
  return equalBytes(expected, hexBytes(signature));
}

async function revokeIndexed(kv, indexKey, reason) {
  await kv.put(`revocation:${indexKey}`, JSON.stringify({ reason, updated_at: new Date().toISOString() }));
  const records = await indexedRecordKeys(kv, indexKey);
  for (const recordKey of records) {
    const record = await kv.get(recordKey, "json");
    if (!record) continue;
    await markRecordRevoked(kv, recordKey, record, reason);
  }
}

async function webhook(request, env) {
  if (!env.LICENSE_STATE || !env.LEMON_WEBHOOK_SECRET) return failure(503, "service_not_configured", "Webhook service is unavailable.");
  let text;
  try { text = await readLimitedText(request, maximumWebhookBytes); }
  catch (error) {
    if (error.message === "request_too_large")
      return failure(413, "request_too_large", "The webhook payload is too large.");
    return failure(400, "invalid_encoding", "The webhook payload is not valid UTF-8.");
  }
  const bytes = encoder.encode(text);
  if (!await validWebhookSignature(bytes, request.headers.get("x-signature"), env.LEMON_WEBHOOK_SECRET)) {
    return failure(401, "invalid_signature", "Invalid webhook signature.");
  }
  let payload;
  try { payload = JSON.parse(text); }
  catch (error) { return failure(400, "invalid_json", "Invalid webhook payload."); }
  const event = String(payload?.meta?.event_name || "");
  const id = String(payload?.data?.id || "");
  const attributes = payload?.data?.attributes || {};
  if (event === "license_key_updated" && id &&
      (attributes.disabled === true || ["disabled", "expired"].includes(String(attributes.status)))) {
    await revokeIndexed(env.LICENSE_STATE, `license:${id}`, `lemon_${String(attributes.status || "disabled")}`);
  } else if (event === "order_refunded" && id) {
    // The signed Lemon event name is authoritative. Lemon's simulated refund
    // event intentionally retains the source order's current `paid` status,
    // so requiring attributes.status === "refunded" makes an otherwise valid
    // delivery a no-op and prevents end-to-end revocation testing.
    await revokeIndexed(env.LICENSE_STATE, `order:${id}`, "order_refunded");
  }
  return response(200, { ok: true });
}

export function createHandler({
  fetchImpl = fetch,
  trustedPublicModulusSha256ByProduct = defaultTrustedPublicModulusSha256ByProduct,
  trustedCommerceByProduct = defaultTrustedCommerceByProduct
} = {}) {
  return {
    async fetch(request, env) {
      const url = new URL(request.url);
      if (request.method === "GET" && ["/health", "/ready"].includes(url.pathname)) {
        return readiness(env, trustedPublicModulusSha256ByProduct, trustedCommerceByProduct);
      }
      if (request.method !== "POST") return failure(405, "method_not_allowed", "Method not allowed.");
      if (url.pathname === "/v1/activate")
        return activate(request, env, fetchImpl, trustedPublicModulusSha256ByProduct,
          trustedCommerceByProduct);
      if (url.pathname === "/v1/deactivate") return deactivate(request, env, fetchImpl);
      if (url.pathname === "/v1/webhooks/lemon") return webhook(request, env);
      return failure(404, "not_found", "Endpoint not found.");
    }
  };
}

export default createHandler();
