import fs from "fs";
import path from "path";

// Local-disk-only debug copy of screenshots captured via the Copy Agent page.
// Not exposed anywhere in the app UI — purely for finding raw captures on disk when
// diagnosing AI detection issues. Never blocks the calling request if it fails.
const BACKUP_ROOT = path.join(process.cwd(), "uploads", "screenshot-backups");

export function backupScreenshots(files: { originalname: string; buffer: Buffer }[]): void {
  try {
    const dateDir = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
    const dir = path.join(BACKUP_ROOT, dateDir);
    fs.mkdirSync(dir, { recursive: true });
    for (const file of files) {
      const safeName = `${Date.now()}_${file.originalname.replace(/[/\\?%*:|"<>]/g, "-")}`;
      fs.writeFileSync(path.join(dir, safeName), file.buffer);
    }
  } catch (err) {
    console.error("[screenshotBackup] failed to write backup:", err);
  }
}
