'use strict'; const fs = require('fs'); const os = require('os'); const path = require('path'); const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs'); const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024; function padNumber (value) { return String(Math.max(0, Number(value) || 0)).padStart(2, '0'); } function localDateStamp (timestampMs) { const date = new Date(Number.isFinite(timestampMs) ? timestampMs : Date.now()); return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`; } function sanitiseVideoName (videoName) { const raw = path.basename(String(videoName || '').trim() || 'unknown-video'); const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, ''); return cleaned || 'unknown-video'; } function subtitleDebugLogFilePath (videoName, timestampMs = Date.now()) { const fileName = `${localDateStamp(timestampMs)}-${sanitiseVideoName(videoName)}-subtitlelog.txt`; return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName); } function ensureSubtitleDebugLogDir () { fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true }); } function serialiseLogEntry (entry) { const payload = entry && typeof entry === 'object' ? entry : { value: entry }; const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString(); return `[${timestamp}] ${JSON.stringify(payload)}\n`; } function directoryEntriesWithStats (dirPath) { let entries = []; try { entries = fs.readdirSync(dirPath, { withFileTypes: true }); } catch { return []; } const out = []; for (const entry of entries) { if (!entry.isFile()) continue; const fullPath = path.join(dirPath, entry.name); try { const stat = fs.statSync(fullPath); out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 }); } catch { // Ignore files that disappear mid-scan. } } return out; } function getSubtitleDebugLogSnapshot () { const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR); const latestFile = entries.slice().sort((a, b) => b.mtimeMs - a.mtimeMs)[0] || null; return { path: SUBTITLE_DEBUG_LOG_DIR, exists: fs.existsSync(SUBTITLE_DEBUG_LOG_DIR), bytes: entries.reduce((sum, entry) => sum + entry.size, 0), files: entries.length, directories: 0, latestFile, }; } function pruneSubtitleDebugLogDir () { ensureSubtitleDebugLogDir(); const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs); let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0); for (const entry of entries) { if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break; try { fs.unlinkSync(entry.fullPath); totalBytes = Math.max(0, totalBytes - entry.size); } catch { // Ignore prune failures; logging must remain best-effort. } } } function appendSubtitleDebugEntries ({ videoName, entries, context = null }) { const rows = Array.isArray(entries) ? entries.filter(Boolean) : []; if (!rows.length) return null; const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs)); const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now()); try { ensureSubtitleDebugLogDir(); const text = rows.map((entry) => { const payload = context && typeof context === 'object' ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) } : entry; return serialiseLogEntry(payload); }).join(''); fs.appendFileSync(targetPath, text, 'utf8'); pruneSubtitleDebugLogDir(); return targetPath; } catch { return null; } } module.exports = { SUBTITLE_DEBUG_LOG_DIR, MAX_SUBTITLE_DEBUG_LOG_BYTES, getSubtitleDebugLogSnapshot, subtitleDebugLogFilePath, pruneSubtitleDebugLogDir, appendSubtitleDebugEntries, };