import { app, desktopCapturer, screen } from 'electron' import { Worker } from 'node:worker_threads' import { existsSync, mkdirSync, readdirSync } from 'fs' import { join } from 'path' const CAPTURE_INTERVAL_MS = 1000 const ROLLING_WINDOW_MS = 7 * 60 * 60 * 1000 let worker: Worker | null = null let intervalHandle: ReturnType | null = null function captureDir(): string { const dir = join(app.getPath('userData'), 'coach-captures') if (!existsSync(dir)) mkdirSync(dir, { recursive: true }) return dir } function ensureWorker(): Worker { if (worker) return worker worker = new Worker(join(__dirname, 'captureWorker.js')) worker.on('error', (error) => console.error('[coach] erreur worker de capture', error)) return worker } async function captureOnce(): Promise { const display = screen.getPrimaryDisplay() const sources = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: display.size }) const source = sources[0] if (!source) return const png = source.thumbnail.toPNG() const filePath = join(captureDir(), `capture-${Date.now()}.png`) ensureWorker().postMessage({ filePath, png }) } function purgeOldCaptures(): void { const cutoff = Date.now() - ROLLING_WINDOW_MS ensureWorker().postMessage({ purgeDir: captureDir(), cutoff }) } let tickCount = 0 export function startVisionCapture(): void { if (intervalHandle) return intervalHandle = setInterval(() => { tickCount += 1 captureOnce().catch((error) => console.error('[coach] echec capture ecran', error)) if (tickCount % 60 === 0) purgeOldCaptures() }, CAPTURE_INTERVAL_MS) } export function stopVisionCapture(): void { if (intervalHandle) { clearInterval(intervalHandle) intervalHandle = null } } export function getRecentCaptures(count: number): string[] { const dir = captureDir() if (!existsSync(dir)) return [] return readdirSync(dir) .filter((f: string) => f.endsWith('.png')) .sort() .slice(-count) .map((f: string) => join(dir, f)) }