#!/usr/bin/env node
import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { existsSync, readFileSync, watchFile, writeFileSync } from "fs";
import { join } from "path";
import { homedir } from "os";
import { execSync } from "child_process";
const RESPONSE_PATH = join(
  homedir(),
  ".stackmemory",
  "sms-latest-response.json"
);
const SIGNAL_PATH = join(homedir(), ".stackmemory", "sms-signal.txt");
let lastProcessedTimestamp = "";
function checkForResponse() {
  try {
    if (existsSync(RESPONSE_PATH)) {
      const data = JSON.parse(
        readFileSync(RESPONSE_PATH, "utf8")
      );
      if (data.timestamp !== lastProcessedTimestamp) {
        lastProcessedTimestamp = data.timestamp;
        return data;
      }
    }
  } catch {
  }
  return null;
}
function triggerNotification(response) {
  const message = `SMS Response: "${response.response}"`;
  try {
    execSync(
      `osascript -e 'display notification "${message}" with title "StackMemory"'`,
      {
        stdio: "ignore"
      }
    );
  } catch {
  }
  process.stdout.write("\x07");
  try {
    writeFileSync(
      SIGNAL_PATH,
      JSON.stringify({
        type: "sms_response",
        response: response.response,
        promptId: response.promptId,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      })
    );
  } catch {
  }
  console.log(`
[SMS] User responded: "${response.response}"`);
  console.log(`[SMS] Run: stackmemory notify run-actions
`);
}
function startResponseWatcher(intervalMs = 2e3) {
  console.log("[SMS Watcher] Watching for responses...");
  console.log("[SMS Watcher] Press Ctrl+C to stop\n");
  const initial = checkForResponse();
  if (initial) {
    triggerNotification(initial);
  }
  setInterval(() => {
    const response = checkForResponse();
    if (response) {
      triggerNotification(response);
    }
  }, intervalMs);
}
function startFileWatcher() {
  console.log("[SMS Watcher] Watching for responses (file mode)...");
  watchFile(RESPONSE_PATH, { interval: 1e3 }, () => {
    const response = checkForResponse();
    if (response) {
      triggerNotification(response);
    }
  });
}
if (process.argv[1]?.includes("sms-watcher")) {
  startResponseWatcher();
}
export {
  checkForResponse,
  startFileWatcher,
  startResponseWatcher,
  triggerNotification
};
//# sourceMappingURL=sms-watcher.js.map
