// --- WALL-E Listening Skill: Audio Chunk Storage ---
// Storage location: DATA_DIR/recordings/{recordingId}/
// DATA_DIR comes from process.env.WALL_E_DATA_DIR || ~/.walle/data

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

function _dataDir() {
  return process.env.WALL_E_DATA_DIR || path.join(process.env.HOME, '.walle', 'data');
}
function _recordingsDir() {
  return path.join(_dataDir(), 'recordings');
}

function ensureDir(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

function saveChunk(recordingId, buffer, index) {
  const dir = path.join(_recordingsDir(), recordingId);
  ensureDir(dir);
  const chunkPath = path.join(dir, `chunk-${String(index).padStart(5, '0')}.webm`);
  fs.writeFileSync(chunkPath, buffer);
  return { path: chunkPath, size: buffer.length };
}

function finalizeRecording(recordingId) {
  const dir = path.join(_recordingsDir(), recordingId);
  if (!fs.existsSync(dir)) throw new Error('Recording directory not found');
  const chunks = fs.readdirSync(dir)
    .filter(f => f.startsWith('chunk-') && f.endsWith('.webm'))
    .sort();
  if (chunks.length === 0) throw new Error('No chunks found');
  const outPath = path.join(dir, 'recording.webm');
  // Concatenate synchronously to ensure file is complete before returning
  const buffers = chunks.map(c => fs.readFileSync(path.join(dir, c)));
  const combined = Buffer.concat(buffers);
  fs.writeFileSync(outPath, combined);
  return { path: outPath, size: combined.length, chunks: chunks.length };
}

function getRecordingPath(recordingId) {
  return path.join(_recordingsDir(), recordingId, 'recording.webm');
}

function getRecordingDir(recordingId) {
  return path.join(_recordingsDir(), recordingId);
}

function deleteRecording(recordingId) {
  const dir = path.join(_recordingsDir(), recordingId);
  if (fs.existsSync(dir)) {
    fs.rmSync(dir, { recursive: true, force: true });
  }
}

function cleanupOldRecordings(maxAgeDays = 90) {
  const recDir = _recordingsDir();
  ensureDir(recDir);
  const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
  let cleaned = 0;
  for (const entry of fs.readdirSync(recDir)) {
    const dir = path.join(recDir, entry);
    try {
      const stat = fs.statSync(dir);
      if (stat.isDirectory() && stat.mtimeMs < cutoff) {
        fs.rmSync(dir, { recursive: true, force: true });
        cleaned++;
      }
    } catch {}
  }
  return cleaned;
}

function getRecordingsDir() { return _recordingsDir(); }

module.exports = {
  saveChunk, finalizeRecording, getRecordingPath, getRecordingDir,
  deleteRecording, cleanupOldRecordings, getRecordingsDir, ensureDir
};
