import { readFileSync, writeFileSync, existsSync, appendFileSync } from "node:fs"; import { type Config } from "./types"; export function sleep(ms: number): Promise { return new Promise((r) => setTimeout(r, ms)); } export function readFile(filePath: string): string[] { if (!existsSync(filePath)) return []; return readFileSync(filePath, "utf-8") .split("\n") .map((s) => s.trim()) .filter((s) => s && !s.startsWith("#")); } // NEW: System Log Writer export function appendLog(fileName: string, message: string): void { try { const timestamp = new Date().toISOString(); // Simple log line const logLine = `[${timestamp}] ${message}\n`; appendFileSync(fileName, logLine, "utf-8"); } catch (err) { // Fail silently or print to console if debugging } } export function formatElapsed(start: Date): string { const diff = Math.max(0, Math.floor((Date.now() - start.getTime()) / 1000)); const hrs = Math.floor(diff / 3600); const mins = Math.floor((diff % 3600) / 60); const secs = diff % 60; if (hrs > 0) return `${hrs}h ${mins}m`; if (mins > 0) return `${mins}m ${secs}s`; return `${secs}s`; } export function rid(length: number = 6): string { return [...Array(length)].map(() => Math.random().toString(36)[2]).join(""); } // --- Config Persistence (Saving/Loading settings) --- const CONFIG_FILE = "config.json"; export function loadConfig(defaults: Config): Config { try { if (existsSync(CONFIG_FILE)) { const fileContent = readFileSync(CONFIG_FILE, "utf-8"); const saved = JSON.parse(fileContent); // Merge saved data with defaults return { ...defaults, ...saved }; } } catch (err) { console.error("⚠️ Could not load config.json, using defaults."); } return defaults; } export function saveConfigToFile(config: Config): void { try { writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8"); } catch (err) { console.error("❌ Failed to save config:", err); } }