'use strict';

/**
 * Usage reporting — TECH_SPEC_V5 §3, "usage reporting (unchanged)".
 *
 * OPT-IN, OFF BY DEFAULT. This is the "no silent telemetry" invariant (§2) made
 * concrete: nothing is collected or sent unless ENABLE_USAGE_REPORTING is
 * explicitly true AND a licence server is configured to send to.
 *
 * What it reports, and nothing more:
 *   - an aggregate count of RPC calls the bot made, per reporting period
 *
 * What it must NEVER report — enforced by there being no code path that reads
 * them: wallet address, balances, trades, profit, pairs, thresholds, IP, or
 * anything that identifies what the customer is doing beyond a bare call count.
 *
 * The counter is a plain integer incremented locally. Reports are POSTed to the
 * licence server's /api/telemetry/usage on an interval, then the counter resets.
 * A failed report is dropped, not retried into a growing backlog — usage data
 * is the least important thing this bot does and must never affect trading.
 */

const DEFAULT_INTERVAL_MS = 6 * 60 * 60 * 1000; // 6 hours

function createUsageTracker({ env = process.env, licenseKey, fetchImpl = globalThis.fetch, logger = console } = {}) {
  const enabled = String(env.ENABLE_USAGE_REPORTING).toLowerCase() === 'true';
  const baseUrl = env.LICENSE_SERVER_BASE_URL
    ? String(env.LICENSE_SERVER_BASE_URL).trim().replace(/\/+$/, '')
    : null;
  const intervalMs = Number(env.USAGE_REPORT_INTERVAL_MS || DEFAULT_INTERVAL_MS);

  let rpcCount = 0;
  let timer = null;

  // Always safe to call. When reporting is off it still counts locally (cheap),
  // but nothing ever leaves the machine.
  function countRpc(n) {
    rpcCount += n || 1;
  }

  async function report() {
    if (!enabled || !baseUrl || !licenseKey) return;
    if (rpcCount === 0) return; // nothing to say

    const total = rpcCount;
    rpcCount = 0; // reset up front; a failed send simply loses this period

    try {
      await fetchImpl(baseUrl + '/api/telemetry/usage', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          key: licenseKey,
          periodEnd: Date.now(),
          // Aggregate only. Deliberately no per-endpoint breakdown, no pairs,
          // no wallet — a single number.
          totalCount: total,
        }),
      });
    } catch (err) {
      // Dropped on purpose. Telemetry must never affect the bot.
    }
  }

  function start() {
    if (!enabled) return false;
    if (!baseUrl || !licenseKey) {
      logger.warn &&
        logger.warn(
          'ENABLE_USAGE_REPORTING is true but LICENSE_SERVER_BASE_URL or LICENSE_KEY ' +
            'is unset — usage reporting stays off.'
        );
      return false;
    }
    timer = setInterval(report, intervalMs);
    if (timer.unref) timer.unref();
    return true;
  }

  function stop() {
    if (timer) { clearInterval(timer); timer = null; }
  }

  return { countRpc, report, start, stop, enabled: enabled && Boolean(baseUrl && licenseKey), get count() { return rpcCount; } };
}

module.exports = { createUsageTracker, DEFAULT_INTERVAL_MS };
