/**
 * Append-only JSONL logger for Engine 2 training.
 *
 * Each resolved prop becomes one line. Files rotate monthly:
 *   data/training/resolutions-2026-06.jsonl
 *
 * Fire-and-forget: logResolution() returns void and swallows errors so a
 * disk-full or permission issue can never break the resolution endpoint.
 * Operationally, monitor disk usage and surface alerts separately.
 *
 * IMPORTANT: `data/` MUST be a persistent Docker volume in Coolify.
 * Otherwise every redeploy nukes the training corpus.
 */

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

// Under test, write to a throwaway temp dir instead of the tracked
// data/training corpus — otherwise every `npm test` appends resolution rows
// to data/training/resolutions-YYYY-MM.jsonl and dirties the git tree
// (Session 31 audit finding; fixed Session 32). `TRAINING_DATA_DIR` lets
// operators override the location explicitly.
const ROOT = process.env.TRAINING_DATA_DIR
  || (process.env.NODE_ENV === 'test'
    ? path.join(os.tmpdir(), 'vyndr-training-test')
    : path.join(process.cwd(), 'data', 'training'));
let initialized = false;

function ensureDir() {
  if (initialized) return;
  try {
    fs.mkdirSync(ROOT, { recursive: true });
    initialized = true;
  } catch (err) {
    console.warn('[jsonlLogger] mkdir failed:', err.message);
  }
}

function monthKey(date = new Date()) {
  const y = date.getUTCFullYear();
  const m = String(date.getUTCMonth() + 1).padStart(2, '0');
  return `${y}-${m}`;
}

function logResolution(data) {
  // Never throw. Resolution must not fail because of a logging issue.
  try {
    ensureDir();
    const file = path.join(ROOT, `resolutions-${monthKey()}.jsonl`);
    const line = JSON.stringify({ ts: new Date().toISOString(), ...data }) + '\n';
    fs.appendFileSync(file, line);
  } catch (err) {
    console.warn('[jsonlLogger] append failed:', err.message);
  }
}

module.exports = { logResolution, monthKey };
