'use strict';

const crypto = require('crypto');
const logger = require('../utils/logger');
const { getAgentConfig, isConfigured } = require('./agentConfig');
const { sendLiveSnapshot } = require('./syncClient');

let lastHash = '';
let lastSentAt = 0;
let inFlight = false;
const SNAPSHOT_KEEPALIVE_MS = Math.max(15000, Number(process.env.ARKHON_LIVE_SNAPSHOT_KEEPALIVE_MS || 45000));

function hashSnapshot(snapshot) {
  return crypto.createHash('sha256').update(JSON.stringify(snapshot || {})).digest('hex');
}

async function pushLiveSnapshot(snapshot) {
  if (!snapshot || inFlight) return;
  const config = getAgentConfig();
  if (!isConfigured(config)) return;

  const snapshotHash = hashSnapshot(snapshot);
  // Cloud snapshots expire. Keep an unchanged snapshot alive so an open table
  // does not disappear merely because nobody edited the account.
  if (snapshotHash === lastHash && Date.now() - lastSentAt < SNAPSHOT_KEEPALIVE_MS) return;

  inFlight = true;
  try {
    await sendLiveSnapshot(config, {
      snapshot_hash: snapshotHash,
      source_generated_at: snapshot._cache?.generado || new Date().toISOString(),
      payload: snapshot,
    });
    lastHash = snapshotHash;
    lastSentAt = Date.now();
  } catch (err) {
    logger.warn({ event: 'agent_live_snapshot_failed', error: err.message });
  } finally {
    inFlight = false;
  }
}

module.exports = { pushLiveSnapshot, hashSnapshot };
