// 比賽狀態儲存:記憶體 Map + JSON 檔案持久化(重啟後按鈕仍可用) import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import { dirname } from 'node:path' export function createStore(filePath) { const matches = new Map() if (filePath && existsSync(filePath)) { try { const data = JSON.parse(readFileSync(filePath, 'utf8')) for (const [key, value] of Object.entries(data)) matches.set(key, value) } catch (error) { console.warn('讀取狀態檔失敗,將以空白狀態啟動:', error.message) } } function persist() { if (!filePath) return try { mkdirSync(dirname(filePath), { recursive: true }) writeFileSync(filePath, JSON.stringify(Object.fromEntries(matches)), 'utf8') } catch (error) { console.warn('寫入狀態檔失敗:', error.message) } } const keyOf = (chatId, messageId) => `${chatId}:${messageId}` return { get: (chatId, messageId) => matches.get(keyOf(chatId, messageId)) ?? null, set(chatId, messageId, match) { matches.set(keyOf(chatId, messageId), match) persist() }, delete(chatId, messageId) { matches.delete(keyOf(chatId, messageId)) persist() }, size: () => matches.size, } }