/**
 * `madarx status` — compact local snapshot. Network-light: a short localhost
 * probe to see if the web tier is up, plus a READ-ONLY DB read (never getDb(),
 * so no schema/seeds/daemons side effects) and a couple of file checks.
 */

import fs from 'node:fs';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { resolveHome } from './home.js';
import { readVersion } from './dispatch.js';

function readUpdateCheck(layout) {
  try {
    return JSON.parse(fs.readFileSync(layout.updateCheckFile, 'utf8'));
  } catch {
    return null;
  }
}

function whatsappPaired(layout) {
  // Baileys writes creds.json into the session dir once a number is linked.
  return fs.existsSync(path.join(layout.dataDir, 'whatsapp', 'session', 'creds.json'));
}

function dbStat(layout) {
  const dbFile = path.join(layout.dataDir, 'madarx.sqlite');
  if (!fs.existsSync(dbFile)) return { initialized: false };
  let db;
  try {
    db = new DatabaseSync(dbFile, { readOnly: true });
    const safe = (fn, dflt = null) => { try { return fn(); } catch { return dflt; } };
    const pending = safe(() => db.prepare("SELECT COUNT(*) AS c FROM approval_requests WHERE status = 'pending'").get().c, null);
    const agents = safe(() => db.prepare('SELECT COUNT(*) AS c FROM agents').get().c, null);
    const lastHeartbeat = safe(() => db.prepare('SELECT MAX(updated_at) AS m FROM heartbeat_tasks').get().m, null);
    return { initialized: true, pendingApprovals: pending, agents, lastHeartbeat };
  } catch (err) {
    return { initialized: true, error: err.message };
  } finally {
    try { db?.close(); } catch {}
  }
}

async function webUp() {
  try {
    const res = await fetch('http://127.0.0.1:8787/api/state', { signal: AbortSignal.timeout(700) });
    return res.ok || res.status === 401 || res.status === 403;
  } catch {
    return false;
  }
}

export async function gatherStatus() {
  const layout = resolveHome();
  return {
    version: readVersion(),
    home: layout.home,
    web: await webUp(),
    update: readUpdateCheck(layout),
    whatsappPaired: whatsappPaired(layout),
    db: dbStat(layout),
  };
}

export async function status() {
  const s = await gatherStatus();
  const line = (k, v) => console.log(`  ${k.padEnd(20)} ${v}`);
  console.log('madarx status\n');
  line('version', s.version);
  line('data home', s.home);
  line('web tier', s.web ? 'up — http://127.0.0.1:8787/' : 'down');
  if (s.update && s.update.behind) line('update', `v${s.update.latest} available  (run: madarx update)`);
  else line('update', s.update ? 'up to date' : 'unknown (no check yet)');
  line('whatsapp', s.whatsappPaired ? 'paired' : 'not paired');
  if (s.db.initialized) {
    if (s.db.error) line('database', `error: ${s.db.error}`);
    else {
      line('pending approvals', String(s.db.pendingApprovals ?? '?'));
      if (s.db.agents != null) line('agents', String(s.db.agents));
      if (s.db.lastHeartbeat) line('last heartbeat', s.db.lastHeartbeat);
    }
  } else {
    line('database', 'not initialized — run `madarx` once');
  }
  console.log('');
  return 0;
}
