/**
 * `self_update` tool adapter — the AGENT-facing path to update madarX OS.
 *
 * Registered as risk `irreversible_external`, so an LLM/agent calling this ALWAYS
 * hits the approval gate in executeRegistryTool (no trust-mode auto-bypass). That
 * is the load-bearing guarantee: an agent can never silently replace its own
 * binary. The actual install is delegated to lib/cli/update.js::applyUpdate, the
 * same runner the CLI/dashboard/weekly-job use.
 */

import { applyUpdate } from '../../cli/update.js';
import { runUpdateCheck, currentVersion } from '../../update-check.js';

/**
 * @param {{ confirm?: boolean }} input
 * @returns {Promise<{ ok: boolean, from: string, to: string|null, applied: boolean, message: string }>}
 */
export async function selfUpdate(input = {}) {
  const check = await runUpdateCheck({});
  if (!check.reachable) {
    return { ok: false, from: currentVersion(), to: null, applied: false, message: 'npm registry unreachable' };
  }
  if (!check.behind) {
    return { ok: true, from: check.current, to: check.latest, applied: false, message: 'already up to date' };
  }
  const res = await applyUpdate({ initiatedBy: 'self_update_tool' });
  return {
    ok: res.ok,
    from: res.from,
    to: check.latest,
    applied: res.ok,
    message: res.ok
      ? `updated ${res.from} → v${check.latest}; restart required`
      : `update failed (exit ${res.code})`,
  };
}
