/**
 * $MADARX_HOME resolution for the `madarx` CLI.
 *
 * A global npm install lives in an immutable package directory that is wiped and
 * rewritten on every `npm i -g …@latest` upgrade. Runtime data (SQLite DB,
 * workspace, secrets vault key, WhatsApp session, update-check) therefore must
 * live OUTSIDE the package dir. This module owns that location — modeled on
 * Hermes' $HERMES_HOME (~/.hermes).
 *
 * Default: ~/.madarx  (override with MADARX_HOME).
 *
 * The CLI calls applyHomeEnv() BEFORE importing any runtime module so that
 * lib/paths.js (which derives DATA_DIR/WORKSPACE from MADARX_HOME), lib/master-key.js
 * (which writes the vault key to MADARX_ENV_FILE), and lib/load-env.js all resolve
 * against the home dir. Child processes (web server, WhatsApp daemon) inherit the
 * exported env and resolve identically.
 */

import path from 'node:path';
import os from 'node:os';
import fs from 'node:fs';

/**
 * Resolve the home directory layout. Pure — does not touch the filesystem or
 * mutate process.env. Pass an explicit `home` to override; otherwise reads
 * MADARX_HOME, then falls back to ~/.madarx.
 *
 * @param {{ home?: string, env?: NodeJS.ProcessEnv }} [opts]
 * @returns {{ home: string, dataDir: string, workspace: string, envFile: string,
 *             updateCheckFile: string, logsDir: string, runDir: string }}
 */
export function resolveHome({ home, env = process.env } = {}) {
  const base = path.resolve(
    home || env.MADARX_HOME || path.join(os.homedir(), '.madarx')
  );
  return {
    home: base,
    dataDir: path.join(base, 'data'),
    workspace: path.join(base, 'workspace'),
    envFile: path.join(base, '.env.local'),
    updateCheckFile: path.join(base, '.update_check'),
    logsDir: path.join(base, 'logs'),
    runDir: path.join(base, 'run'),
  };
}

/**
 * Create the home directory skeleton (idempotent). The home dir and its run/logs
 * children get mode 700 — it holds the master key and session credentials, so it
 * must not be world-readable.
 */
export function ensureHome(layout) {
  fs.mkdirSync(layout.home, { recursive: true, mode: 0o700 });
  for (const dir of [layout.dataDir, layout.workspace, layout.logsDir, layout.runDir]) {
    fs.mkdirSync(dir, { recursive: true });
  }
  try { fs.chmodSync(layout.home, 0o700); } catch {}
  return layout;
}

/**
 * Resolve + create the home dir AND export the env vars that the runtime and all
 * child processes resolve against. Returns the layout.
 *
 * Sets MADARX_HOME (so lib/paths.js derives DATA_DIR/WORKSPACE) and MADARX_ENV_FILE
 * (so the secrets vault key is read/written under the home dir). It deliberately
 * does NOT set MADARX_DATA_DIR — that explicit override doubles as the "running
 * under test isolation" signal that disables the in-process cron/heartbeat
 * daemons, which a real install needs running. See lib/paths.js.
 */
export function applyHomeEnv({ home, env = process.env } = {}) {
  const layout = ensureHome(resolveHome({ home, env }));
  env.MADARX_HOME = layout.home;
  if (!env.MADARX_ENV_FILE) env.MADARX_ENV_FILE = layout.envFile;
  return layout;
}
