import fs from 'fs'; import path from 'path'; const CHAT_HISTORY_FILE = path.join(__dirname, 'chat_history.json'); const MAX_MESSAGES = 100; export interface ChatMessage { id: string; user: string; message: string; timestamp: number; } // Initialize chat history file if it doesn't exist function initializeChatHistory(): void { if (!fs.existsSync(CHAT_HISTORY_FILE)) { fs.writeFileSync(CHAT_HISTORY_FILE, JSON.stringify([], null, 2)); } } export function saveMessage(message: ChatMessage): void { try { initializeChatHistory(); let messages: ChatMessage[] = []; // Read existing messages const fileContent = fs.readFileSync(CHAT_HISTORY_FILE, 'utf-8'); try { messages = JSON.parse(fileContent); if (!Array.isArray(messages)) { messages = []; } } catch (parseError) { console.error('Error parsing chat history file:', parseError); messages = []; } // Add new message messages.push(message); // Keep only the last MAX_MESSAGES if (messages.length > MAX_MESSAGES) { messages = messages.slice(-MAX_MESSAGES); } // Write back to file fs.writeFileSync(CHAT_HISTORY_FILE, JSON.stringify(messages, null, 2)); } catch (error) { console.error('Error saving chat message:', error); } } export function loadRecentMessages(): ChatMessage[] { try { initializeChatHistory(); const fileContent = fs.readFileSync(CHAT_HISTORY_FILE, 'utf-8'); try { const messages: ChatMessage[] = JSON.parse(fileContent); if (!Array.isArray(messages)) { return []; } return messages.slice(-MAX_MESSAGES); } catch (parseError) { console.error('Error parsing chat history file:', parseError); return []; } } catch (error) { console.error('Error loading chat messages:', error); return []; } }