import * as fs from 'fs' import * as path from 'path' const DATA_DIR = fs.existsSync('/data') ? '/data' : '/tmp' const TIMERS_PATH = path.join(DATA_DIR, 'tablet-timers.json') export interface Timer { id: string label: string startedAt: string // ISO endsAt: string // ISO agent?: 'cosmo' | 'lusya' } function load(): Timer[] { try { if (fs.existsSync(TIMERS_PATH)) { return JSON.parse(fs.readFileSync(TIMERS_PATH, 'utf-8')) } } catch {} return [] } function save(list: Timer[]) { try { fs.writeFileSync(TIMERS_PATH, JSON.stringify(list, null, 2)) } catch {} } // Mutative helpers, used by timer API route export function listActive(): Timer[] { const now = Date.now() // Drop any that expired over 30 min ago — stale garbage const list = load().filter(t => new Date(t.endsAt).getTime() > now - 30 * 60 * 1000) save(list) return list } export function addTimer(t: Omit): Timer { const full: Timer = { id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6), startedAt: new Date().toISOString(), ...t, } const list = load() list.push(full) save(list) return full } export function removeTimer(id: string): boolean { const list = load() const next = list.filter(t => t.id !== id) if (next.length === list.length) return false save(next) return true }