'use strict';

const fs = require('fs');
const path = require('path');

function billingEvidenceDir() {
  return path.join(process.env.LOCALAPPDATA || path.join(process.env.USERPROFILE || 'C:\\', 'AppData', 'Local'), 'ARKHON', 'billing');
}

function monitorLogsDir() {
  return path.join(process.env.ProgramData || 'C:\\ProgramData', 'ARKHON Monitor', 'logs');
}

function ensureDir() {
  const dir = billingEvidenceDir();
  fs.mkdirSync(dir, { recursive: true });
  return dir;
}

function evidencePath(fileName) {
  return path.join(ensureDir(), fileName);
}

function safeClone(value) {
  return JSON.parse(JSON.stringify(value || {}, (_key, val) => {
    if (typeof val !== 'string') return val;
    return val
      .replace(/(cfacturacion=)[^&\s]+/ig, '$1***')
      .replace(/(\/t\/)[^/?#\s]+/ig, '$1***')
      .replace(/(password|passwd|pwd|secret|token|key)=([^&\s]+)/ig, '$1=***');
  }));
}

function appendLog(fileName, event, payload = {}) {
  const line = JSON.stringify({
    at: new Date().toISOString(),
    event,
    ...safeClone(payload),
  });
  fs.appendFileSync(evidencePath(fileName), `${line}\n`, 'utf8');
  if (fileName === 'ticket-capture.log') {
    // This ProgramData copy is a compatibility mirror. The primary evidence
    // above is authoritative, so a locked or restricted legacy log must never
    // interrupt ticket processing.
    try {
      const dir = monitorLogsDir();
      fs.mkdirSync(dir, { recursive: true });
      fs.appendFileSync(path.join(dir, fileName), `${line}\n`, 'utf8');
    } catch (_error) {
      // Best effort by design. Avoid logging recursively from this module.
    }
  }
  return line;
}

function writeEvidence(payload = {}) {
  const data = {
    at: new Date().toISOString(),
    ...safeClone(payload),
  };
  fs.writeFileSync(evidencePath('qr-print-evidence.json'), JSON.stringify(data, null, 2), 'utf8');
  return data;
}

module.exports = {
  billingEvidenceDir,
  monitorLogsDir,
  evidencePath,
  appendLog,
  writeEvidence,
};
