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);
  }
}

function getTypeAgentRunDir(runId: string): string {
  const dateDir = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
  return path.join(BACKUP_ROOT, "type-agent", dateDir, runId);
}

// Same convention as backupScreenshots, but grouped under a "type-agent/<date>/<runId>"
// subfolder so every screenshot from one Type Agent run stays together for debugging
// (e.g. "locate" and "confirm" images per step, in click order via the timestamp prefix).
export function backupTypeAgentScreenshot(runId: string, label: string, imageBase64: string): void {
  try {
    const dir = getTypeAgentRunDir(runId);
    fs.mkdirSync(dir, { recursive: true });
    const safeLabel = label.replace(/[/\\?%*:|"<>]/g, "-").slice(0, 80);
    const fileName = `${Date.now()}_${safeLabel}.png`;
    fs.writeFileSync(path.join(dir, fileName), Buffer.from(imageBase64, "base64"));
  } catch (err) {
    console.error("[screenshotBackup] failed to write type-agent backup:", err);
  }
}

// One human-readable line per event (step start/attempt/locate/confirm/click/error), appended
// to run.log in the same per-run folder as that run's screenshots — so opening one folder
// shows both what was clicked and what it looked like at the time, including the exact
// AI-reported ratio for every locate attempt.
export function logTypeAgentStep(runId: string, entry: Record<string, unknown>): void {
  try {
    const dir = getTypeAgentRunDir(runId);
    fs.mkdirSync(dir, { recursive: true });
    const line = `[${new Date().toISOString()}] ${JSON.stringify(entry)}\n`;
    fs.appendFileSync(path.join(dir, "run.log"), line);
  } catch (err) {
    console.error("[screenshotBackup] failed to write type-agent log:", err);
  }
}
