#!/usr/bin/env node
/**
 * Venta desktop node agent.
 *
 * Runs on a paired machine (Docker container or `node agent.mjs` directly) and
 * maintains a secure channel to the Venta API:
 *   - heartbeat every 30s (online status, version, hostname)
 *   - file catalog sync every 60s (the "files" half of the desktop node)
 *   - command pickup + execution + result report (the "terminal" half)
 *
 * Auth: the pairing secret is sent as the `x-node-token` header; the server
 * verifies it against the stored SHA-256 hash. TLS is always used in
 * production (VENTA_API=https://www.venta.tools).
 *
 * Environment:
 *   VENTA_API             API base URL (required)
 *   VENTA_NODE_ID         node uuid returned by pairing (required)
 *   VENTA_NODE_SECRET     pairing secret (required)
 *   VENTA_WATCH_DIRS      comma-separated dirs to catalog (default: /data or $HOME)
 *   VENTA_EXEC_TIMEOUT    per-command timeout in seconds (default 30)
 *   VENTA_HEARTBEAT_MS    heartbeat interval (default 30000)
 *   VENTA_FILES_MS        catalog interval (default 60000)
 *   VENTA_POLL_MS         command poll interval (default 5000)
 *   VENTA_LOG_LEVEL       silent | normal (default normal)
 *   VENTA_STATE_FILE      a file in a directory only you can write: accept the daily rotated credential and keep it there
 */
"use strict";

import { execFile } from "node:child_process";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const API = env("VENTA_API");
const NODE_ID = env("VENTA_NODE_ID");
// Optional: a file this agent may write. With it, the agent accepts the
// credential the server rotates daily and keeps it across restarts; without
// it, the pairing secret is used as given (it lapses after 30 idle days).
const STATE_FILE = process.env.VENTA_STATE_FILE || "";
let SECRET = loadSecret(env("VENTA_NODE_SECRET"));
const WATCH_DIRS = env("VENTA_WATCH_DIRS", os.platform() === "win32" ? os.homedir() : "/data")
  .split(",").map((s) => s.trim()).filter(Boolean);
const EXEC_TIMEOUT_MS = Number(env("VENTA_EXEC_TIMEOUT", "30")) * 1000;
const HEARTBEAT_MS = Number(env("VENTA_HEARTBEAT_MS", "30000"));
const FILES_MS = Number(env("VENTA_FILES_MS", "60000"));
const POLL_MS = Number(env("VENTA_POLL_MS", "5000"));
const LOG = env("VENTA_LOG_LEVEL", "normal") !== "silent";
const VERSION = "1.0.0";
const MAX_FILES = 5000;
const MAX_DEPTH = 6;

// Optional vars pass a fallback; only the three required ones may omit it.
function env(name, fallback) {
  const value = process.env[name];
  if (value) return value;
  if (fallback !== undefined) return fallback;
  console.error(`[venta-node] missing required env var: ${name}`);
  process.exit(1);
}

function log(...args) {
  if (LOG) console.log("[venta-node]", ...args);
}

/** The saved rotated credential for this node, when there is one; else the pairing secret. */
function loadSecret(fallback) {
  if (!STATE_FILE) return fallback;
  try {
    const saved = JSON.parse(fs.readFileSync(STATE_FILE, "utf8"));
    if (saved && saved.nodeId === NODE_ID && typeof saved.secret === "string" && saved.secret) return saved.secret;
  } catch {
    /* no saved credential yet */
  }
  return fallback;
}

// Written to a temporary file and renamed into place, so a crash mid-write never leaves a broken state file.
// The temporary name is random and must not exist yet, so nothing set up in advance can catch the secret.
function saveSecret(secret) {
  const temp = `${STATE_FILE}.${crypto.randomBytes(6).toString("hex")}.tmp`;
  fs.writeFileSync(temp, JSON.stringify({ nodeId: NODE_ID, secret }), { mode: 0o600, flag: "wx" });
  fs.renameSync(temp, STATE_FILE);
}

const shell = process.platform === "win32" ? { cmd: "cmd", args: ["/d", "/s", "/c"] } : { cmd: "/bin/sh", args: ["-c"] };

function url(linkId, suffix) {
  return `${API.replace(/\/$/, "")}/api/desktop-node/${encodeURIComponent(linkId)}${suffix}`;
}

async function api(linkId, method, suffix, body) {
  const response = await fetch(url(linkId, suffix), {
    method,
    headers: {
      "content-type": "application/json",
      "x-node-link-id": linkId,
      "x-node-token": SECRET,
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(20_000),
  });
  if (!response.ok) {
    const text = await response.text().catch(() => "");
    throw new Error(`API ${method} ${suffix} -> ${response.status} ${text.slice(0, 200)}`);
  }
  return response.status === 204 ? null : response.json();
}

let beating = false;
async function heartbeat() {
  // One check-in at a time: two in flight could each be handed a credential.
  if (beating) return;
  beating = true;
  try {
    const answer = await api(NODE_ID, "POST", "/agent", { action: "heartbeat", version: VERSION, hostname: os.hostname(), rotate: Boolean(STATE_FILE) });
    if (STATE_FILE && answer && typeof answer.rotated === "string" && answer.rotated) {
      // Saved first, then used: the old credential keeps working until the new
      // one is, so a credential that could not be kept is simply not taken up.
      try {
        saveSecret(answer.rotated);
        SECRET = answer.rotated;
      } catch (error) {
        log("could not save the new credential; keeping the current one:", error.message);
      }
    }
  } catch (error) {
    log("heartbeat failed:", error.message);
  } finally {
    beating = false;
  }
}

function walk(root, out) {
  let stack = [{ dir: root, rel: "" }];
  while (stack.length > 0 && out.length < MAX_FILES) {
    const { dir, rel } = stack.pop();
    let entries;
    try {
      entries = fs.readdirSync(dir, { withFileTypes: true });
    } catch {
      continue;
    }
    for (const entry of entries) {
      if (out.length >= MAX_FILES) break;
      const full = path.join(dir, entry.name);
      const relPath = rel ? `${rel}/${entry.name}` : entry.name;
      let stat;
      try {
        stat = fs.statSync(full);
      } catch {
        continue;
      }
      out.push({
        path: relPath,
        size: entry.isDirectory() ? 0 : stat.size,
        modifiedAt: stat.mtime.toISOString(),
        isDir: entry.isDirectory(),
      });
      if (entry.isDirectory() && !entry.isSymbolicLink() && rel.split("/").length < MAX_DEPTH) {
        stack.push({ dir: full, rel: relPath });
      }
    }
  }
}

async function syncFiles() {
  const files = [];
  for (const dir of WATCH_DIRS) {
    walk(path.resolve(dir), files);
    if (files.length >= MAX_FILES) break;
  }
  try {
    const { stored } = await api(NODE_ID, "POST", "/agent", { action: "sync-files", files });
    log(`file catalog synced: ${stored} entries`);
  } catch (error) {
    log("file sync failed:", error.message);
  }
}

async function pollCommands() {
  let json;
  try {
    json = await api(NODE_ID, "GET", "/agent");
  } catch (error) {
    log("command poll failed:", error.message);
    return;
  }
  if (!json?.command) return;

  const command = json.command;
  log("executing:", command.command);

  const allowedCwd = command.cwd
    ? WATCH_DIRS.some((dir) => {
        const root = path.resolve(dir);
        const cwd = path.resolve(command.cwd);
        return cwd === root || cwd.startsWith(root + path.sep);
      })
    : false;
  const cwd = allowedCwd ? path.resolve(command.cwd) : undefined;

  const started = Date.now();
  execFile(
    shell.cmd,
    shell.args.concat(command.command),
    {
      cwd,
      timeout: EXEC_TIMEOUT_MS,
      maxBuffer: 64 * 1024 * 1024,
      windowsHide: true,
    },
    (error, stdout, stderr) => {
      const result = {
        commandId: command.id,
        exitCode: error ? (typeof error.code === "number" ? error.code : 1) : 0,
        stdout: String(stdout ?? "").slice(0, 64_000),
        stderr: String(stderr ?? "").slice(0, 64_000),
        finishedAt: new Date().toISOString(),
      };
      if (error && error.killed) result.stderr = (result.stderr + `\n[command timed out after ${EXEC_TIMEOUT_MS / 1000}s]`).trim();
      api(NODE_ID, "POST", "/agent", { action: "result", result })
        .then(() => log(`result reported in ${Date.now() - started}ms (exit ${result.exitCode})`))
        .catch((error) => log("result report failed:", error.message));
    },
  );
}

log(`starting node ${NODE_ID} (v${VERSION}) on ${os.hostname()}`);
log(`watch dirs: ${WATCH_DIRS.join(", ")} | api: ${API}`);

heartbeat();
syncFiles();
setInterval(heartbeat, HEARTBEAT_MS);
setInterval(syncFiles, FILES_MS);
setInterval(pollCommands, POLL_MS);

for (const signal of ["SIGTERM", "SIGINT"]) {
  process.on(signal, () => {
    log("shutting down");
    process.exit(0);
  });
}