/**
 * @file Cross-lane named locks: serialize a machine-thrashing step (a build,
 * an e2e run) across ALL lanes, as opposed to `lane-lock.js`'s per-lane,
 * in-process serialization (a different axis — a separate module on purpose,
 * so the two are never conflated).
 *
 * `mkdir` is the atomicity primitive: it throws `EEXIST` when the directory
 * already exists, so "is it free" and "claim it" are one syscall, never a
 * check-then-create race. No `flock` dependency, unlike Shipyard's original
 * (`brew install flock` on macOS).
 * @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
 */

const fs = require("node:fs");
const path = require("node:path");

const { LANES_ROOT } = require("./worktree");

/**
 * However low `LOCK_MAX_HOLD` is set, a holder younger than this can never be
 * broken. This is what stops an impatient env-var edit from force-breaking a
 * genuinely live holder — the floor is the actual safety property, not the
 * configurable default.
 */
const LOCK_MAX_HOLD_FLOOR_SEC = 300;

/** Where every named lock's directory lives. */
function locksRoot() {
  return path.join(LANES_ROOT, ".locks");
}

/** `Math.max(LOCK_MAX_HOLD env, the 300s floor)`, read per call so a test (or an
 *  operator) can change it without a restart. */
function effectiveMaxHoldSec() {
  const raw = Number(process.env.LOCK_MAX_HOLD);
  const configured = Number.isFinite(raw) && raw > 0 ? raw : 2700;
  return Math.max(configured, LOCK_MAX_HOLD_FLOOR_SEC);
}

function ownerPath(name) {
  return path.join(locksRoot(), name, "owner");
}

/** Parse an owner file's `"<holder> <epochSeconds>"` contents. */
function readOwner(name) {
  let text;
  try {
    text = fs.readFileSync(ownerPath(name), "utf8");
  } catch {
    return null;
  }
  const match = /^(\S+) (\d+)$/.exec(text.trim());
  if (!match) return null;
  const since = Number(match[2]);
  return { holder: match[1], since, ageSec: Math.floor(Date.now() / 1000) - since };
}

/**
 * Try to acquire a named lock once. Never blocks, never retries — the caller
 * (the CLI) owns the polling loop; CCAM's server-side primitives are always
 * single-shot.
 *
 * A stale holder (older than `effectiveMaxHoldSec()`) is broken automatically:
 * its lock directory is removed and the acquire is retried once before
 * answering.
 *
 * @param {string} name - Lock name.
 * @param {string} holder - Identity to record as the owner (e.g. `"lane3"`).
 * @returns {{acquired: true} | {acquired: false, holder: string, since: number, ageSec: number}}
 */
function tryAcquire(name, holder) {
  const dir = path.join(locksRoot(), name);
  fs.mkdirSync(locksRoot(), { recursive: true });

  try {
    fs.mkdirSync(dir);
  } catch (err) {
    if (err.code !== "EEXIST") throw err;
    const owner = readOwner(name);
    if (!owner || owner.ageSec <= effectiveMaxHoldSec()) {
      return owner
        ? { acquired: false, holder: owner.holder, since: owner.since, ageSec: owner.ageSec }
        : { acquired: false, holder: "unknown", since: 0, ageSec: Infinity };
    }
    // Stale — break it and retry once.
    fs.rmSync(dir, { recursive: true, force: true });
    fs.mkdirSync(dir);
  }

  fs.writeFileSync(path.join(dir, "owner"), `${holder} ${Math.floor(Date.now() / 1000)}`);
  return { acquired: true };
}

/**
 * Release a lock. Refuses (throws `ENOTHOLDER`) when `holder` does not match
 * the recorded owner — a release never trusts its caller, the same rule every
 * other destructive path in this project follows.
 *
 * @param {string} name - Lock name.
 * @param {string} holder - Must match the current owner.
 */
function release(name, holder) {
  const owner = readOwner(name);
  if (!owner) {
    throw Object.assign(new Error(`no such lock: ${name}`), { code: "ENOLOCK" });
  }
  if (owner.holder !== holder) {
    throw Object.assign(new Error(`lock "${name}" is held by ${owner.holder}, not ${holder}`), {
      code: "ENOTHOLDER",
      currentHolder: owner.holder,
    });
  }
  fs.rmSync(path.join(locksRoot(), name), { recursive: true, force: true });
}

/** Current state of one named lock, read-only. */
function status(name) {
  const owner = readOwner(name);
  return owner ? { held: true, ...owner } : { held: false };
}

/** Every currently-held lock. */
function listLocks() {
  let entries = [];
  try {
    entries = fs.readdirSync(locksRoot());
  } catch {
    return [];
  }
  return entries
    .map((name) => ({ name, ...status(name) }))
    .filter((lock) => lock.held)
    .map(({ held, ...rest }) => rest);
}

module.exports = {
  LOCK_MAX_HOLD_FLOOR_SEC,
  locksRoot,
  effectiveMaxHoldSec,
  tryAcquire,
  release,
  status,
  listLocks,
};
