import { shq } from "./remote-ssh.mjs";
import { seatProfileShellPath, shellPathAssign } from "./home-path.mjs";
import {
  SEAT_PROXY_BASE,
  SEAT_PROXY_USER,
  SEAT_NETNS_DIR,
  SEAT_PROXY_VERSION,
  SEAT_PROXY_HEALTH_INTERVAL_SEC,
  SEAT_PROXY_HEALTH_TIMEOUT_SEC,
  SEATS_HOME_REL,
  SEAT_STATE_REL,
  SEAT_ACCOUNTS_REL,
} from "./seat-constants.mjs";
import { deriveSeatProxyPort } from "./seat-discovery.mjs";
import {
  buildNetnsCollisionGuardScript,
  buildNetnsOwnerMarkerVerifyScript,
  buildNetnsOwnerMarkerWriteScript,
  buildHostNatApplyScript,
  buildNsNftApplyScript,
  deriveNetnsLayout,
  implementerUsernameForSeat,
  netnsMarkerSudoReadOwner,
  netnsMarkerSudoTestF,
  nftTableExistsAwk,
} from "./seat-netns.mjs";
import { buildAtomicWriteIdempotentScript, contentDigest } from "./seat-atomic.mjs";
import { buildStdinBlobReceiveScript } from "./seat-transfer.mjs";

export function seatProxyInstanceDir(seatId) {
  return `${SEAT_PROXY_BASE}/${seatId}`;
}

export function seatNetnsPath(seatId) {
  return `${SEAT_NETNS_DIR}/overdeck-seat-${seatId}`;
}

export function buildSeatProxyBaseUrl(nsIp, port) {
  return `http://${nsIp}:${port}/v1`;
}

export function buildSeatProxyEnvContent({ seatId, boundModel, port, nsIp }) {
  const configDir = `${SEAT_PROXY_BASE}/${seatId}/`;
  return `CCP_CODEX_MODEL=${boundModel}\nCCP_CONFIG_DIR=${configDir}\nPORT=${port}\nCCP_BIND_ADDRESS=${nsIp}\n`;
}

export function buildSeatProxyEnvWriteScript({ seatId, boundModel, port, nsIp }) {
  const dir = seatProxyInstanceDir(seatId);
  const envFile = `${dir}/seat-proxy.env`;
  const content = buildSeatProxyEnvContent({ seatId, boundModel, port, nsIp });
  const digest = contentDigest(content);
  const b64 = Buffer.from(content, "utf8").toString("base64");
  return [
    "set -euo pipefail",
    `seat_id=${shq(seatId)}`,
    `dir=${shq(dir)}`,
    `env_file=${shq(envFile)}`,
    `want=${shq(digest)}`,
    "sudo -n install -d -o root -g overdeck-seat-proxy -m 0710 /var/lib/overdeck/seat-proxy",
    "sudo -n install -d -o overdeck-seat-proxy -g overdeck-seat-proxy -m 0700 \"$dir\"",
    "tmp=$(mktemp)",
    `python3 -c 'import base64,sys; sys.stdout.buffer.write(base64.b64decode(sys.argv[1]))' ${shq(b64)} >"$tmp"`,
    "actual=$(sha256sum \"$tmp\" | awk '{print $1}')",
    "[ \"$actual\" = \"$want\" ] || { echo seat-proxy-env-digest; exit 1; }",
    "sudo -n install -o root -g root -m 0600 \"$tmp\" \"$env_file\"",
    "rm -f \"$tmp\"",
    "sudo -n /usr/local/bin/overdeck-seat-proxy-validate \"$seat_id\"",
  ].join("\n");
}

export function buildIpForwardPrereqScript() {
  return [
    "set -euo pipefail",
    "sudo -n install -d -m 0755 /etc/sysctl.d",
    "cat <<'OD_IP_FORWARD' | sudo -n tee /etc/sysctl.d/99-overdeck-seat-forward.conf >/dev/null",
    "net.ipv4.ip_forward=1",
    "OD_IP_FORWARD",
    "sudo -n /sbin/sysctl -w net.ipv4.ip_forward=1 >/dev/null",
    "read_forward=$(/sbin/sysctl -n net.ipv4.ip_forward 2>/dev/null || echo 0)",
    '[ "$read_forward" = "1" ] || { echo ip-forward-disabled; exit 1; }',
  ].join("\n");
}

export function buildNetnsProvisionScript(seatId, port = deriveSeatProxyPort(seatId)) {
  const layout = deriveNetnsLayout(seatId);
  const implementerUser = implementerUsernameForSeat(seatId);
  const {
    netnsName,
    netnsPath,
    vethHost,
    vethNs,
    hostIp,
    nsIp,
    hostPrefix,
    nsPrefix,
    subnet,
    nftTable,
    natTable,
  } = layout;
  return [
    buildIpForwardPrereqScript(),
    buildNetnsCollisionGuardScript(layout, port),
    "set -euo pipefail",
    `netns=${shq(netnsPath)}`,
    `netns_name=${shq(netnsName)}`,
    `veth_host=${shq(vethHost)}`,
    `veth_ns=${shq(vethNs)}`,
    `host_ip=${shq(hostIp)}`,
    `ns_ip=${shq(nsIp)}`,
    `host_prefix=${shq(hostPrefix)}`,
    `ns_prefix=${shq(nsPrefix)}`,
    `subnet=${shq(subnet)}`,
    `nft_table=${shq(nftTable)}`,
    `nat_table=${shq(natTable)}`,
    "sudo -n mkdir -p /var/run/netns",
    "if [ ! -e \"$netns\" ]; then",
    "  sudo -n ip netns add \"$netns_name\"",
    "  sudo -n ip link add \"$veth_host\" type veth peer name \"$veth_ns\"",
    "  sudo -n ip link set \"$veth_ns\" netns \"$netns_name\"",
    "  sudo -n ip addr add \"$host_prefix\" dev \"$veth_host\"",
    "  sudo -n ip link set \"$veth_host\" up",
    "  sudo -n ip netns exec \"$netns_name\" ip addr add \"$ns_prefix\" dev \"$veth_ns\"",
    "  sudo -n ip netns exec \"$netns_name\" ip link set lo up",
    "  sudo -n ip netns exec \"$netns_name\" ip link set \"$veth_ns\" up",
    "  sudo -n ip netns exec \"$netns_name\" ip route add default via \"$host_ip\" dev \"$veth_ns\"",
    "fi",
    "read_host=$(ip -o addr show dev \"$veth_host\" | awk '/inet / {print $4}' | head -1)",
    "[ \"$read_host\" = \"$host_prefix\" ] || { echo netns-host-addr-drift; exit 1; }",
    "read_ns=$(sudo -n ip netns exec \"$netns_name\" ip -o addr show dev \"$veth_ns\" | awk '/inet / {print $4}' | head -1)",
    "[ \"$read_ns\" = \"$ns_prefix\" ] || { echo netns-peer-addr-drift; exit 1; }",
    buildNsNftApplyScript(layout, { port, implementerUser }),
    buildHostNatApplyScript(layout),
    buildNetnsOwnerMarkerWriteScript(layout, port),
    buildNetnsOwnerMarkerVerifyScript(layout),
    "[ -e \"$netns\" ] || { echo netns-missing; exit 1; }",
  ].join("\n");
}

export function buildProxyUnitStartScript(seatId) {
  return [
    "set -euo pipefail",
    `unit=overdeck-seat-proxy@${seatId}.service`,
    "sudo -n systemctl start \"$unit\"",
    "sudo -n systemctl is-active --quiet \"$unit\" || { echo proxy-unit-not-active; exit 1; }",
  ].join("\n");
}

export function buildProxyHealthScript(seatId, port) {
  const layout = deriveNetnsLayout(seatId);
  const implementerUser = implementerUsernameForSeat(seatId);
  const maxAttempts = Math.ceil(SEAT_PROXY_HEALTH_TIMEOUT_SEC / SEAT_PROXY_HEALTH_INTERVAL_SEC);
  return [
    "set -euo pipefail",
    `netns_name=${shq(layout.netnsName)}`,
    `ns_ip=${shq(layout.nsIp)}`,
    `port=${port}`,
    `implementer_user=${shq(implementerUser)}`,
    'implementer_uid=$(id -u "$implementer_user" 2>/dev/null || { echo netns-implementer-user-missing; exit 1; })',
    `health_url="http://\${ns_ip}:\${port}/healthz"`,
    `health_interval=${SEAT_PROXY_HEALTH_INTERVAL_SEC}`,
    `max_attempts=${maxAttempts}`,
    "healthy=0",
    "attempt=0",
    'while [ "$attempt" -lt "$max_attempts" ]; do',
    '  if sudo -n ip netns exec "$netns_name" sudo -n -u "#$implementer_uid" curl -fsS "$health_url" >/dev/null 2>&1; then',
    "    healthy=1",
    "    break",
    "  fi",
    '  attempt=$((attempt + 1))',
    '  [ "$attempt" -lt "$max_attempts" ] || break',
    '  sleep "$health_interval"',
    "done",
    '[ "$healthy" = "1" ] || { echo proxy-health-timeout; exit 1; }',
  ].join("\n");
}

export function buildProxyStopScript(seatId) {
  return [
    "set -euo pipefail",
    `unit=overdeck-seat-proxy@${seatId}.service`,
    "if sudo -n systemctl is-active --quiet \"$unit\"; then sudo -n systemctl stop \"$unit\"; fi",
    "sudo -n systemctl reset-failed \"$unit\" 2>/dev/null || true",
  ].join("\n");
}

export function buildNetnsTeardownScript(seatId) {
  const layout = deriveNetnsLayout(seatId);
  const natExistsAwk = nftTableExistsAwk("ip", "nat_table");
  return [
    "set -euo pipefail",
    `netns=${shq(layout.netnsPath)}`,
    `netns_name=${shq(layout.netnsName)}`,
    `veth_host=${shq(layout.vethHost)}`,
    `nat_table=${shq(layout.natTable)}`,
    `marker=${shq(layout.markerPath)}`,
    "owner=\"\"",
    `if ${netnsMarkerSudoTestF('"$marker"')}; then`,
    `  owner=$(${netnsMarkerSudoReadOwner('"$marker"')} 2>/dev/null || echo "")`,
    `  [ -z "$owner" ] || [ "$owner" = ${shq(layout.seatId)} ] || { echo netns-marker-collision; exit 1; }`,
    "fi",
    "if ip link show \"$veth_host\" >/dev/null 2>&1; then",
    `  if [ -n "$owner" ] && [ "$owner" != ${shq(layout.seatId)} ]; then echo netns-veth-collision; exit 1; fi`,
    "  sudo -n ip link del \"$veth_host\" 2>/dev/null || true",
    "fi",
    "if [ -e \"$netns\" ]; then sudo -n ip netns del \"$netns_name\" 2>/dev/null || true; fi",
    "if sudo -n nft list tables 2>/dev/null | awk " + natExistsAwk + " | grep -q .; then",
    `  if [ -n "$owner" ] && [ "$owner" != ${shq(layout.seatId)} ]; then echo netns-nat-collision; exit 1; fi`,
    "  sudo -n nft delete table ip \"$nat_table\" 2>/dev/null || true",
    "fi",
    `if ${netnsMarkerSudoTestF('"$marker"')}; then sudo -n rm -f "$marker"; fi`,
  ].join("\n");
}

export function buildCodexAuthMetadataValidateScript({
  authPathExpr = '"$dir/auth.json"',
  parentDirExpr = '"$dir"',
} = {}) {
  const owner = `${SEAT_PROXY_USER}:${SEAT_PROXY_USER}`;
  return [
    `auth_path=${authPathExpr}`,
    `parent_dir=${parentDirExpr}`,
    '[ "$(sudo -n stat -c \'%F\' "$auth_path")" = "regular file" ] || { echo codex-auth-not-regular; exit 1; }',
    `[ "$(sudo -n stat -c '%U:%G' "$auth_path")" = "${owner}" ] || { echo codex-auth-owner; exit 1; }`,
    '[ "$(sudo -n stat -c \'%a\' "$auth_path")" = "600" ] || { echo codex-auth-mode; exit 1; }',
    '[ "$(sudo -n stat -c \'%F\' "$parent_dir")" = "directory" ] || { echo codex-auth-parent-not-dir; exit 1; }',
    `[ "$(sudo -n stat -c '%U:%G' "$parent_dir")" = "${owner}" ] || { echo codex-auth-parent-owner; exit 1; }`,
    '[ "$(sudo -n stat -c \'%a\' "$parent_dir")" = "700" ] || { echo codex-auth-parent-mode; exit 1; }',
  ];
}

export function buildCodexAuthCleanupScript() {
  const prefix = `${SEAT_PROXY_BASE}/`;
  return [
    `case "$dir" in ${prefix}*/codex) ;; *) echo codex-auth-cleanup-path; exit 1 ;; esac`,
    `case "$proxy_dir" in ${prefix}*) ;; *) echo codex-auth-cleanup-path; exit 1 ;; esac`,
    'sudo -n rm -f "$dir/auth.json" 2>/dev/null || true',
    'sudo -n rmdir "$dir" 2>/dev/null || true',
    'sudo -n rmdir "$proxy_dir" 2>/dev/null || true',
  ];
}

export function buildCodexAuthInstallFromStdin(seatId) {
  const proxyDir = seatProxyInstanceDir(seatId);
  const dir = `${proxyDir}/codex`;
  return buildStdinBlobReceiveScript([
    `dir=${shq(dir)}`,
    `proxy_dir=${shq(proxyDir)}`,
    "auth_installed=0",
    "auth_tmp=",
    "cleanup_auth() {",
    '  if [ "$auth_installed" = "1" ]; then return 0; fi',
    '  if [ -n "${auth_tmp:-}" ]; then sudo -n rm -f "$auth_tmp" 2>/dev/null || true; fi',
    "}",
    "trap 'cleanup_auth' EXIT",
    `sudo -n install -d -o ${SEAT_PROXY_USER} -g ${SEAT_PROXY_USER} -m 0700 "$dir"`,
    'auth_tmp=$(sudo -n mktemp "$dir/.auth-install.XXXXXX")',
    `sudo -n install -o ${SEAT_PROXY_USER} -g ${SEAT_PROXY_USER} -m 0600 "$tmp" "$auth_tmp"`,
    ...buildCodexAuthMetadataValidateScript({ authPathExpr: '"$auth_tmp"' }),
    'sudo -n mv -f "$auth_tmp" "$dir/auth.json"',
    "auth_tmp=",
    "auth_installed=1",
    "trap - EXIT",
  ]);
}

export const ACCOUNT_TAR_ALLOWLIST = [
  "account_identity.json",
];

export const ACCOUNT_TAR_PREVALIDATE_PY = `import json, os, sys, tarfile

def fail(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)

allow = set(json.loads(os.environ["OD_ALLOWLIST"]))
tar_path = os.environ["OD_TAR"]
profile = os.environ.get("OD_PROFILE", "")
if profile and os.path.exists(profile):
    fail("account-profile-exists")
with tarfile.open(tar_path, "r:gz") as tf:
    for member in tf.getmembers():
        name = member.name
        if name.startswith("/") or name.startswith("../") or "/../" in f"/{name}":
            fail(f"account-tar-absolute:{name}")
        norm = os.path.normpath(name)
        if norm.startswith("..") or norm == ".":
            fail(f"account-tar-escape:{name}")
        top = norm.split("/")[0]
        if top not in allow:
            fail(f"account-tar-entry:{name}")
        if member.issym() or member.islnk():
            fail(f"account-tar-link:{name}")
        if not (member.isfile() or member.isdir()):
            fail(f"account-tar-special:{name}")
`;

export const ACCOUNT_TAR_POSTVALIDATE_PY = `import json, os, stat, sys

def fail(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)

def mode_ok(path):
    st = os.lstat(path)
    if stat.S_ISDIR(st.st_mode):
        return (st.st_mode & 0o777) == 0o700
    if stat.S_ISREG(st.st_mode):
        return (st.st_mode & 0o777) == 0o600
    return False

allow = set(json.loads(os.environ["OD_ALLOWLIST"]))
staging = os.environ["OD_STAGING"]
profile = os.environ.get("OD_PROFILE", "")
if profile and os.path.exists(profile):
    fail("account-profile-exists")
for root, dirs, files in os.walk(staging, topdown=True, followlinks=False):
    rel_root = os.path.relpath(root, staging)
    if rel_root == ".":
        rel_root = ""
    for name in list(dirs) + files:
        rel = name if not rel_root else f"{rel_root}/{name}"
        top = rel.split("/")[0]
        if top not in allow:
            fail(f"account-tar-staging-entry:{rel}")
        path = os.path.join(root, name)
        if os.path.islink(path):
            fail(f"account-tar-staging-link:{rel}")
        if not mode_ok(path):
            fail(f"account-tar-staging-mode:{rel}")
`;

export function buildAccountTarRestoreFromStdin(identity) {
  const profile = seatProfileShellPath(identity.accountSlug, identity.seatId);
  const allowJson = shq(JSON.stringify(ACCOUNT_TAR_ALLOWLIST));
  return buildStdinBlobReceiveScript([
    "set -euo pipefail",
    shellPathAssign("profile", profile),
    'staging="$profile.restore-staging.$$"',
    "if [ -e \"$profile\" ]; then echo account-profile-exists; exit 1; fi",
    "cleanup() { rm -rf \"$staging\"; }",
    "trap cleanup EXIT",
    "mkdir -p \"$staging\"",
    "chmod 700 \"$staging\"",
    `OD_TAR="$tmp" OD_PROFILE="$profile" OD_ALLOWLIST=${allowJson} python3 - <<'PY'`,
    ACCOUNT_TAR_PREVALIDATE_PY.trim(),
    "PY",
    "if ! tar -xzf \"$tmp\" -C \"$staging\"; then echo account-tar-extract-failed; exit 1; fi",
    `OD_STAGING="$staging" OD_PROFILE="$profile" OD_ALLOWLIST=${allowJson} python3 - <<'PY'`,
    ACCOUNT_TAR_POSTVALIDATE_PY.trim(),
    "PY",
    "if [ -e \"$profile\" ]; then echo account-profile-exists; exit 1; fi",
    "mv -T \"$staging\" \"$profile\"",
    "trap - EXIT",
    "umask 077",
    "mkdir -p \"$profile/secure-storage\"",
    "chmod 700 \"$profile\"",
    "touch \"$profile/.restore-complete\"",
    "chmod 600 \"$profile/.restore-complete\"",
  ]);
}

export function buildExistenceProbeScript({ seatId, accountSlug }) {
  return [
    "set -euo pipefail",
    `profile="$HOME/${SEAT_ACCOUNTS_REL}/${accountSlug}/${seatId}"`,
    `state_dir="$HOME/${SEAT_STATE_REL}/${seatId}"`,
    `seat_home="$HOME/${SEATS_HOME_REL}/${seatId}"`,
    `proxy_dir="${SEAT_PROXY_BASE}/${seatId}"`,
    `netns="${seatNetnsPath(seatId)}"`,
    'printf "profile=%s\\n" "$([ -e "$profile" ] && echo 1 || echo 0)"',
    'printf "state_dir=%s\\n" "$([ -e "$state_dir" ] && echo 1 || echo 0)"',
    'printf "seat_home=%s\\n" "$([ -e "$seat_home" ] && echo 1 || echo 0)"',
    'printf "proxy_dir=%s\\n" "$(if sudo -n test -d "$proxy_dir"; then echo 1; else echo 0; fi)"',
    'printf "netns=%s\\n" "$([ -e "$netns" ] && echo 1 || echo 0)"',
  ].join("\n");
}

export function parseExistenceProbe(stdout) {
  const out = {};
  for (const line of String(stdout || "").split("\n")) {
    const m = line.match(/^(\w+)=([01])$/);
    if (m) out[m[1]] = m[2] === "1";
  }
  return out;
}

function rollbackStopScopeScript(unitExpr) {
  return [
    `unit=${unitExpr}`,
    "if systemctl --user is-active --quiet \"$unit\"; then systemctl --user stop \"$unit\" || true; fi",
    "sleep 0.2",
  ];
}

function rollbackTmuxScript(socketExpr) {
  return [
    `socket=${socketExpr}`,
    "if [ -S \"$socket\" ]; then tmux -S \"$socket\" kill-server 2>/dev/null || true; rm -f \"$socket\"; fi",
  ];
}

function rollbackRemoveIfNew(pathExpr, existedKey, label) {
  const seatsPrefix = `$HOME/${SEATS_HOME_REL}/`;
  return [
    `path=${pathExpr}`,
    `existed=${existedKey}`,
    'if [ "$existed" != "1" ]; then',
    `  case "$path" in ${seatsPrefix}*) ;; *) echo rollback-path-reject:${label}; exit 1 ;; esac`,
    '  if [ -e "$path" ]; then rm -rf "$path"; fi',
    "fi",
  ];
}

function rollbackRemoveProfileIfNew(profileExpr, accountSlug, seatId, existedKey) {
  return [
    `profile=${profileExpr}`,
    `account=${shq(accountSlug)}`,
    `seat_id=${shq(seatId)}`,
    `existed=${existedKey}`,
    'if [ "$existed" != "1" ]; then',
    `  want="$HOME/${SEAT_ACCOUNTS_REL}/$account/$seat_id"`,
    '  [ "$profile" = "$want" ] || { echo rollback-profile-path; exit 1; }',
    '  if [ -e "$profile" ]; then rm -rf "$profile"; fi',
    "fi",
  ];
}

function rollbackRemoveStateIfNew(stateExpr, seatId, existedKey) {
  return [
    `state_dir=${stateExpr}`,
    `seat_id=${shq(seatId)}`,
    `existed=${existedKey}`,
    'if [ "$existed" != "1" ]; then',
    `  want="$HOME/${SEAT_STATE_REL}/$seat_id"`,
    '  [ "$state_dir" = "$want" ] || { echo rollback-state-path; exit 1; }',
    '  if [ -e "$state_dir" ]; then rm -rf "$state_dir"; fi',
    "fi",
  ];
}

function rollbackRemoveProxyIfNew(seatId, existedKey) {
  const proxyDir = `${SEAT_PROXY_BASE}/${seatId}`;
  return [
    `seat_id=${shq(seatId)}`,
    `proxy_dir=${shq(proxyDir)}`,
    `existed=${existedKey}`,
    'if [ "$existed" != "1" ]; then',
    `  want="${SEAT_PROXY_BASE}/$seat_id"`,
    '  [ "$proxy_dir" = "$want" ] || { echo rollback-proxy-path; exit 1; }',
    buildProxyStopScript(seatId),
    '  if sudo -n test -e "$proxy_dir"; then sudo -n rm -rf "$proxy_dir"; fi',
    "fi",
  ];
}

function rollbackVerifyAbsentIfNew(pathExpr, label, existedKey, { rootSafe = false } = {}) {
  const testCmd = rootSafe ? `sudo -n test -e ${pathExpr}` : `[ -e ${pathExpr} ]`;
  return [
    `if [ ${existedKey} != "1" ]; then`,
    `  if ${testCmd}; then echo rollback-leftover:${label}; exit 1; fi`,
    "fi",
  ];
}

export function buildRollbackVerifyLines(seatId, identity, existed) {
  return [
    ...rollbackVerifyAbsentIfNew(`"${SEAT_PROXY_BASE}/${seatId}"`, "proxy-dir", existed.proxy_dir ? "1" : "0", { rootSafe: true }),
    ...rollbackVerifyAbsentIfNew(`"${seatNetnsPath(seatId)}"`, "netns", existed.netns ? "1" : "0"),
    ...rollbackVerifyAbsentIfNew(`"$HOME/${SEAT_STATE_REL}/${seatId}"`, "state-dir", existed.state_dir ? "1" : "0"),
    ...rollbackVerifyAbsentIfNew(`"$HOME/${SEAT_ACCOUNTS_REL}/${identity.accountSlug}/${seatId}"`, "profile", existed.profile ? "1" : "0"),
    ...rollbackVerifyAbsentIfNew(`"$HOME/${SEATS_HOME_REL}/${seatId}"`, "seat-home", existed.seat_home ? "1" : "0"),
  ];
}

export function buildRollbackScript(seatId, identity, options = {}) {
  const mode = options.mode ?? "minimal";
  const existed = options.existed ?? {};
  const unit = `agent-seat-${seatId}.scope`;
  const socket = `$HOME/${SEAT_STATE_REL}/${seatId}/tmux.sock`;
  const stateDir = `"$HOME/${SEAT_STATE_REL}/${seatId}"`;
  const profile = `"$HOME/${SEAT_ACCOUNTS_REL}/${identity.accountSlug}/${seatId}"`;
  const seatHome = `"$HOME/${SEATS_HOME_REL}/${seatId}"`;

  const lines = [
    "set -euo pipefail",
    ...rollbackStopScopeScript(shq(unit)),
    ...rollbackTmuxScript(shq(socket)),
  ];

  if (mode === "create") {
    lines.push(
      ...rollbackRemoveProxyIfNew(seatId, existed.proxy_dir ? "1" : "0"),
    );
    if (!existed.netns) {
      lines.push(buildNetnsTeardownScript(seatId));
    }
    lines.push(
      ...rollbackRemoveStateIfNew(stateDir, seatId, existed.state_dir ? "1" : "0"),
      ...rollbackRemoveProfileIfNew(profile, identity.accountSlug, seatId, existed.profile ? "1" : "0"),
      ...rollbackRemoveIfNew(seatHome, existed.seat_home ? "1" : "0", "seat-home"),
      ...buildRollbackVerifyLines(seatId, identity, existed),
    );
  }

  return lines.join("\n");
}

export function buildSeatMetadataProxy(seatId, boundModel, port, layout) {
  const configDir = `${SEAT_PROXY_BASE}/${seatId}/`;
  const nsIp = layout?.nsIp ?? deriveNetnsLayout(seatId).nsIp;
  return {
    required: true,
    pinnedVersion: SEAT_PROXY_VERSION,
    ccpCodexModel: boundModel,
    unit: `overdeck-seat-proxy@${seatId}.service`,
    configDir,
    envFile: `${configDir}seat-proxy.env`,
    port,
    bindAddress: nsIp,
    baseUrl: buildSeatProxyBaseUrl(nsIp, port),
  };
}

export function planSeatProxy({ seatId, boundModel }) {
  const port = deriveSeatProxyPort(seatId);
  const layout = deriveNetnsLayout(seatId);
  return {
    seatId,
    boundModel,
    port,
    netnsPath: layout.netnsPath,
    netnsName: layout.netnsName,
    layout,
    nsIp: layout.nsIp,
    proxyBaseUrl: buildSeatProxyBaseUrl(layout.nsIp, port),
    configDir: seatProxyInstanceDir(seatId),
    envFile: `${seatProxyInstanceDir(seatId)}/seat-proxy.env`,
    envContent: buildSeatProxyEnvContent({ seatId, boundModel, port, nsIp: layout.nsIp }),
    unit: `overdeck-seat-proxy@${seatId}.service`,
    proxyUser: SEAT_PROXY_USER,
  };
}

export function validateSeatProxyEnvAllowlist(content, { seatId, boundModel, port, nsIp }) {
  const lines = String(content).trimEnd().split("\n");
  const values = {};
  for (const line of lines) {
    if (!line || line.startsWith("#")) return { ok: false, reason: "env-comment" };
    const idx = line.indexOf("=");
    if (idx < 1) return { ok: false, reason: "env-malformed" };
    const key = line.slice(0, idx);
    const value = line.slice(idx + 1);
    if (values[key]) return { ok: false, reason: "env-duplicate" };
    values[key] = value;
  }
  const expectedDir = `${SEAT_PROXY_BASE}/${seatId}/`;
  if (values.CCP_CODEX_MODEL !== boundModel) return { ok: false, reason: "ccp-model" };
  if (values.CCP_CONFIG_DIR !== expectedDir) return { ok: false, reason: "ccp-config-dir" };
  if (values.PORT !== String(port)) return { ok: false, reason: "port" };
  if (values.CCP_BIND_ADDRESS !== nsIp) return { ok: false, reason: "ccp-bind-address" };
  if (values.CCP_BIND_ADDRESS === "127.0.0.1" || values.CCP_BIND_ADDRESS === "localhost") {
    return { ok: false, reason: "ccp-bind-loopback" };
  }
  return { ok: true, values };
}

export { buildAtomicWriteIdempotentScript, contentDigest };
