/**
 * Recursive data nesting guard.
 *
 * In past versions, a buggy update/restore path created data/data/data/...
 * directories — each containing a full recursive copy of the parent.
 * This module runs at startup, detects and removes nested duplicates.
 *
 * Add to app.js: require('./utilities/nesting-guard')();
 */

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

module.exports = function nestingGuard() {
  try {
    const paths = require('../config/paths');
    const dataDir = paths && paths.dataDir;
    // Defensive: if paths.dataDir is undefined (older callers or a future
    // export-shape drift), fall back to platformPaths.dataDir directly so the
    // guard can still execute. Pre-fix this branch was swallowed silently by
    // the outer try/catch, leaving the entire nesting-guard a no-op (DC-077).
    const effectiveDataDir = typeof dataDir === 'string' && dataDir
      ? dataDir
      : require('../../platform-paths').dataDir;
    if (typeof effectiveDataDir !== 'string' || !effectiveDataDir) {
      console.warn('[nesting-guard] Skipped: dataDir unavailable from src/config/paths and platform-paths');
      return;
    }
    const dataDataPath = path.join(effectiveDataDir, 'data');

    // If data/data exists, it's a recursive duplicate — remove it
    if (fs.existsSync(dataDataPath)) {
      const stat = fs.statSync(dataDataPath);
      if (stat.isDirectory()) {
        // Verify it's truly a duplicate (contains config.json like the parent)
        const markerFile = path.join(dataDataPath, 'config.json');
        const parentMarker = path.join(dataDir, 'config.json');
        if (fs.existsSync(markerFile) && fs.existsSync(parentMarker)) {
          console.log('[nesting-guard] Removing recursive data nesting: ' + dataDataPath);
          fs.rmSync(dataDataPath, { recursive: true, force: true });
          console.log('[nesting-guard] Recursive nesting removed');
        }
      }
    }
  } catch (e) {
    // Non-fatal — don't crash startup over cleanup
    console.warn('[nesting-guard] Skipped: ' + e.message);
  }
};
