#!/usr/bin/env node
/**
 * File Watcher for Automatic FTP Deployment
 * Watches D:\SMS for changes and auto-deploys to FTPS
 *
 * Usage: node watch-deploy.js
 */

const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");

const WATCH_DIR = __dirname;
const DEBOUNCE_MS = 1000; // Wait 1s before deploying
const IGNORE_PATTERNS = [
  "/.git/",
  "/.vscode/",
  "/node_modules/",
  "messages.json",
  "token_cache.json",
  "webhook_log.json",
  ".env",
  "watch-deploy.js",
  ".DS_Store",
  "Thumbs.db",
];

let deployTimeout = null;
let lastDeploy = 0;
const MIN_DEPLOY_INTERVAL = 3000; // Minimum 3s between deploys

function shouldIgnore(filePath) {
  const relativePath = path.relative(WATCH_DIR, filePath);
  return IGNORE_PATTERNS.some((pattern) => {
    if (pattern.endsWith("/")) {
      return filePath.includes(pattern);
    }
    return relativePath.includes(pattern) || relativePath.endsWith(pattern);
  });
}

function formatTime() {
  return new Date().toLocaleTimeString();
}

function deploy() {
  const now = Date.now();
  const timeSinceLast = now - lastDeploy;

  if (timeSinceLast < MIN_DEPLOY_INTERVAL) {
    console.log(`[${formatTime()}] ⏱ Skipping deploy (too soon, waiting...)`);
    // Reschedule to ensure the changes are not lost
    clearTimeout(deployTimeout);
    deployTimeout = setTimeout(deploy, MIN_DEPLOY_INTERVAL - timeSinceLast);
    return;
  }

  lastDeploy = now;
  console.log(`\n[${formatTime()}] 🚀 Deploying to FTP server...`);

  const child = spawn("php", ["deploy.php"], {
    cwd: WATCH_DIR,
    stdio: "inherit",
  });

  child.on("close", (code) => {
    if (code === 0) {
      console.log(`[${formatTime()}] ✓ Deploy successful\n`);
    } else {
      console.log(`[${formatTime()}] ✗ Deploy failed (exit code: ${code})\n`);
    }
  });

  child.on("error", (err) => {
    console.error(`[${formatTime()}] ✗ Deploy error: ${err.message}\n`);
  });
}

function triggerDeploy() {
  clearTimeout(deployTimeout);
  deployTimeout = setTimeout(deploy, DEBOUNCE_MS);
}

function watchDirectory(dir) {
  try {
    fs.watch(dir, { recursive: true }, (eventType, filename) => {
      if (!filename) return;

      const filePath = path.join(dir, filename);

      // Skip ignored files
      if (shouldIgnore(filePath)) {
        return;
      }

      // Only watch actual file changes (not directory listings)
      if (eventType === "change") {
        console.log(`[${formatTime()}] 📝 ${filename} changed`);
        triggerDeploy();
      } else if (eventType === "rename") {
        console.log(`[${formatTime()}] ➕ ${filename} added/deleted`);
        triggerDeploy();
      }
    });
  } catch (err) {
    console.error("Error setting up file watcher:", err);
  }
}

console.log(`
╔══════════════════════════════════════════════════════════════╗
║          SMS App - File Watcher & FTP Deployer               ║
╚══════════════════════════════════════════════════════════════╝

📂 Watching: ${WATCH_DIR}
🔗 Target:  ftps://ftp.shanesmith.com.au:21
⏱ Debounce: ${DEBOUNCE_MS}ms
🛡 Ignored:  ${IGNORE_PATTERNS.slice(0, 3).join(", ")}...

[${formatTime()}] ✓ Watcher ready. Making changes to files will trigger FTP upload.
[${formatTime()}] Press Ctrl+C to stop.

`);

watchDirectory(WATCH_DIR);

// Handle graceful shutdown
process.on("SIGINT", () => {
  console.log("\n[Stopping watcher...]\n");
  process.exit(0);
});
