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, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
import { homedir } from "os";
import { execSync } from "child_process";
const QUEUE_PATH = join(homedir(), ".stackmemory", "sms-action-queue.json");
function loadActionQueue() {
  try {
    if (existsSync(QUEUE_PATH)) {
      return JSON.parse(readFileSync(QUEUE_PATH, "utf8"));
    }
  } catch {
  }
  return { actions: [], lastChecked: (/* @__PURE__ */ new Date()).toISOString() };
}
function saveActionQueue(queue) {
  try {
    const dir = join(homedir(), ".stackmemory");
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true });
    }
    writeFileSync(QUEUE_PATH, JSON.stringify(queue, null, 2));
  } catch {
  }
}
function queueAction(promptId, response, action) {
  const queue = loadActionQueue();
  const id = Math.random().toString(36).substring(2, 10);
  queue.actions.push({
    id,
    promptId,
    response,
    action,
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    status: "pending"
  });
  saveActionQueue(queue);
  return id;
}
function getPendingActions() {
  const queue = loadActionQueue();
  return queue.actions.filter((a) => a.status === "pending");
}
function markActionRunning(id) {
  const queue = loadActionQueue();
  const action = queue.actions.find((a) => a.id === id);
  if (action) {
    action.status = "running";
    saveActionQueue(queue);
  }
}
function markActionCompleted(id, result, error) {
  const queue = loadActionQueue();
  const action = queue.actions.find((a) => a.id === id);
  if (action) {
    action.status = error ? "failed" : "completed";
    action.result = result;
    action.error = error;
    saveActionQueue(queue);
  }
}
function executeAction(action) {
  markActionRunning(action.id);
  try {
    console.log(`[sms-action] Executing: ${action.action}`);
    const output = execSync(action.action, {
      encoding: "utf8",
      timeout: 6e4,
      // 1 minute timeout
      stdio: ["pipe", "pipe", "pipe"]
    });
    markActionCompleted(action.id, output);
    return { success: true, output };
  } catch (err) {
    const error = err instanceof Error ? err.message : String(err);
    markActionCompleted(action.id, void 0, error);
    return { success: false, error };
  }
}
function processAllPendingActions() {
  const pending = getPendingActions();
  let succeeded = 0;
  let failed = 0;
  for (const action of pending) {
    const result = executeAction(action);
    if (result.success) {
      succeeded++;
    } else {
      failed++;
    }
  }
  return { processed: pending.length, succeeded, failed };
}
function cleanupOldActions() {
  const queue = loadActionQueue();
  const completed = queue.actions.filter(
    (a) => a.status === "completed" || a.status === "failed"
  );
  if (completed.length > 50) {
    const toRemove = completed.slice(0, completed.length - 50);
    queue.actions = queue.actions.filter(
      (a) => !toRemove.find((r) => r.id === a.id)
    );
    saveActionQueue(queue);
    return toRemove.length;
  }
  return 0;
}
const ACTION_TEMPLATES = {
  // Git/PR actions
  approvePR: (prNumber) => `gh pr review ${prNumber} --approve && gh pr merge ${prNumber} --auto`,
  requestChanges: (prNumber) => `gh pr review ${prNumber} --request-changes -b "Changes requested via SMS"`,
  mergePR: (prNumber) => `gh pr merge ${prNumber} --squash`,
  closePR: (prNumber) => `gh pr close ${prNumber}`,
  // Deployment actions
  deploy: (env = "production") => `npm run deploy:${env}`,
  rollback: (env = "production") => `npm run rollback:${env}`,
  verifyDeployment: (url) => `curl -sf ${url}/health || exit 1`,
  // Build actions
  rebuild: () => `npm run build`,
  retest: () => `npm test`,
  lint: () => `npm run lint:fix`,
  // Notification actions
  notifySlack: (message) => `curl -X POST $SLACK_WEBHOOK -d '{"text":"${message}"}'`,
  notifyTeam: (message) => `stackmemory notify send "${message}" --title "Team Alert"`
};
function createAction(template, ...args) {
  const fn = ACTION_TEMPLATES[template];
  if (typeof fn === "function") {
    return fn(...args);
  }
  return fn;
}
function startActionWatcher(intervalMs = 5e3) {
  console.log(
    `[sms-action] Starting action watcher (interval: ${intervalMs}ms)`
  );
  return setInterval(() => {
    const pending = getPendingActions();
    if (pending.length > 0) {
      console.log(`[sms-action] Found ${pending.length} pending action(s)`);
      processAllPendingActions();
    }
  }, intervalMs);
}
function handleSMSResponse(promptId, response, action) {
  if (action) {
    const actionId = queueAction(promptId, response, action);
    console.log(`[sms-action] Queued action ${actionId}: ${action}`);
  }
}
export {
  ACTION_TEMPLATES,
  cleanupOldActions,
  createAction,
  executeAction,
  getPendingActions,
  handleSMSResponse,
  loadActionQueue,
  markActionCompleted,
  markActionRunning,
  processAllPendingActions,
  queueAction,
  saveActionQueue,
  startActionWatcher
};
//# sourceMappingURL=sms-action-runner.js.map
