import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { createServer } from "http";
import { parse as parseUrl } from "url";
import { existsSync, writeFileSync, mkdirSync, readFileSync } from "fs";
import { join } from "path";
import { homedir } from "os";
import { processIncomingResponse, loadSMSConfig } from "./sms-notify.js";
import { queueAction } from "./sms-action-runner.js";
function parseFormData(body) {
  const params = new URLSearchParams(body);
  const result = {};
  params.forEach((value, key) => {
    result[key] = value;
  });
  return result;
}
function storeLatestResponse(promptId, response, action) {
  const dir = join(homedir(), ".stackmemory");
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true });
  }
  const responsePath = join(dir, "sms-latest-response.json");
  writeFileSync(
    responsePath,
    JSON.stringify({
      promptId,
      response,
      action,
      timestamp: (/* @__PURE__ */ new Date()).toISOString()
    })
  );
}
function handleSMSWebhook(payload) {
  const { From, Body } = payload;
  console.log(`[sms-webhook] Received from ${From}: ${Body}`);
  const result = processIncomingResponse(From, Body);
  if (!result.matched) {
    if (result.prompt) {
      return {
        response: `Invalid response. Expected: ${result.prompt.options.map((o) => o.key).join(", ")}`
      };
    }
    return { response: "No pending prompt found." };
  }
  storeLatestResponse(
    result.prompt?.id || "unknown",
    result.response || Body,
    result.action
  );
  if (result.action) {
    const actionId = queueAction(
      result.prompt?.id || "unknown",
      result.response || Body,
      result.action
    );
    console.log(`[sms-webhook] Queued action ${actionId}: ${result.action}`);
    return {
      response: `Got it! Queued action: ${result.action.substring(0, 30)}...`,
      action: result.action,
      queued: true
    };
  }
  return {
    response: `Received: ${result.response}. Next action will be triggered.`
  };
}
function twimlResponse(message) {
  return `<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Message>${escapeXml(message)}</Message>
</Response>`;
}
function escapeXml(str) {
  return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
}
function startWebhookServer(port = 3456) {
  const server = createServer(
    async (req, res) => {
      const url = parseUrl(req.url || "/", true);
      if (url.pathname === "/health") {
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ status: "ok" }));
        return;
      }
      if ((url.pathname === "/sms" || url.pathname === "/sms/incoming" || url.pathname === "/webhook") && req.method === "POST") {
        let body = "";
        req.on("data", (chunk) => {
          body += chunk;
        });
        req.on("end", () => {
          try {
            const payload = parseFormData(
              body
            );
            const result = handleSMSWebhook(payload);
            res.writeHead(200, { "Content-Type": "text/xml" });
            res.end(twimlResponse(result.response));
          } catch (err) {
            console.error("[sms-webhook] Error:", err);
            res.writeHead(500, { "Content-Type": "text/xml" });
            res.end(twimlResponse("Error processing message"));
          }
        });
        return;
      }
      if (url.pathname === "/sms/status" && req.method === "POST") {
        let body = "";
        req.on("data", (chunk) => {
          body += chunk;
        });
        req.on("end", () => {
          try {
            const payload = parseFormData(body);
            console.log(
              `[sms-webhook] Status update: ${payload["MessageSid"]} -> ${payload["MessageStatus"]}`
            );
            const statusPath = join(
              homedir(),
              ".stackmemory",
              "sms-status.json"
            );
            const statuses = existsSync(statusPath) ? JSON.parse(readFileSync(statusPath, "utf8")) : {};
            statuses[payload["MessageSid"]] = payload["MessageStatus"];
            writeFileSync(statusPath, JSON.stringify(statuses, null, 2));
            res.writeHead(200, { "Content-Type": "text/plain" });
            res.end("OK");
          } catch (err) {
            console.error("[sms-webhook] Status error:", err);
            res.writeHead(500);
            res.end("Error");
          }
        });
        return;
      }
      if (url.pathname === "/status") {
        const config = loadSMSConfig();
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(
          JSON.stringify({
            enabled: config.enabled,
            pendingPrompts: config.pendingPrompts.length
          })
        );
        return;
      }
      res.writeHead(404);
      res.end("Not found");
    }
  );
  server.listen(port, () => {
    console.log(`[sms-webhook] Server listening on port ${port}`);
    console.log(
      `[sms-webhook] Incoming messages: http://localhost:${port}/sms/incoming`
    );
    console.log(
      `[sms-webhook] Status callback:   http://localhost:${port}/sms/status`
    );
    console.log(`[sms-webhook] Configure these URLs in Twilio console`);
  });
}
function smsWebhookMiddleware(req, res) {
  const result = handleSMSWebhook(req.body);
  res.type("text/xml");
  res.send(twimlResponse(result.response));
}
if (process.argv[1]?.endsWith("sms-webhook.js")) {
  const port = parseInt(process.env["SMS_WEBHOOK_PORT"] || "3456", 10);
  startWebhookServer(port);
}
export {
  handleSMSWebhook,
  smsWebhookMiddleware,
  startWebhookServer
};
//# sourceMappingURL=sms-webhook.js.map
