import { d as defineEventHandler, a as useOrchestrator, t as toWebRequest, k as getRequestHeader, s as setResponseStatus, l as shouldHandleComment, h as useNitroApp, m as handleIssueCommentMention, n as handleWebhook, e as setResponseHeader, o as createVerify, j as createLogger } from '../../../../index.mjs';
import process from 'node:process';
import '@anthropic-ai/claude-agent-sdk';
import '@octokit/webhooks';
import 'node:events';
import 'node:buffer';
import 'node:fs';
import 'node:path';
import 'node:crypto';
import 'consola';
import '@octokit/graphql';
import 'zod';
import '@octokit/auth-app';
import 'node:os';
import '@libsql/client';
import 'liquidjs';
import 'js-yaml';
import 'node:child_process';
import '@chat-adapter/github';
import '@chat-adapter/slack';
import 'chat';
import 'chat-adapter-asana';
import 'better-auth';
import 'better-auth/plugins';
import 'bun:sqlite';
import 'better-auth/db/migration';
import 'node:url';
import '@iconify/utils';
import 'rou3';

const log = createLogger("webhook");
const verifierCache = /* @__PURE__ */ new Map();
function getVerifier(secret) {
  let verifier = verifierCache.get(secret);
  if (!verifier) {
    verifier = createVerify(secret);
    verifierCache.set(secret, verifier);
  }
  return verifier;
}
function createGitHubRestApi(token, apiEndpoint = "https://api.github.com") {
  const headers = {
    "Authorization": `token ${token}`,
    "Accept": "application/vnd.github+json",
    "X-GitHub-Api-Version": "2022-11-28"
  };
  return {
    async addReaction(owner, repo, commentId, reaction) {
      const res = await fetch(
        `${apiEndpoint}/repos/${owner}/${repo}/issues/comments/${commentId}/reactions`,
        {
          method: "POST",
          headers: { ...headers, "Content-Type": "application/json" },
          body: JSON.stringify({ content: reaction })
        }
      );
      if (!res.ok)
        throw new Error(`GitHub addReaction failed: ${res.status} ${await res.text()}`);
      const data = await res.json();
      return { id: data.id };
    },
    async removeReaction(owner, repo, commentId, reactionId) {
      const res = await fetch(
        `${apiEndpoint}/repos/${owner}/${repo}/issues/comments/${commentId}/reactions/${reactionId}`,
        { method: "DELETE", headers }
      );
      if (!res.ok && res.status !== 404)
        throw new Error(`GitHub removeReaction failed: ${res.status} ${await res.text()}`);
    },
    async postComment(owner, repo, issueNumber, body) {
      const res = await fetch(
        `${apiEndpoint}/repos/${owner}/${repo}/issues/${issueNumber}/comments`,
        {
          method: "POST",
          headers: { ...headers, "Content-Type": "application/json" },
          body: JSON.stringify({ body })
        }
      );
      if (!res.ok)
        throw new Error(`GitHub postComment failed: ${res.status} ${await res.text()}`);
    }
  };
}
const github_post = defineEventHandler(async (event) => {
  var _a, _b, _c, _d;
  const orchestrator = useOrchestrator();
  const config = orchestrator.getConfig();
  const { secret, events } = config.server.webhook;
  const request = toWebRequest(event);
  if (secret) {
    const verify2 = getVerifier(secret);
    const signature = (_a = getRequestHeader(event, "x-hub-signature-256")) != null ? _a : "";
    const body2 = await request.clone().text();
    const valid = await verify2(body2, signature).catch((err) => {
      log.error("signature verification error:", err);
      return false;
    });
    if (!valid) {
      setResponseStatus(event, 401);
      return { error: { code: "invalid_signature", message: "Signature verification failed" } };
    }
  }
  const githubEvent = getRequestHeader(event, "x-github-event");
  const nitroApp = useNitroApp();
  const chatBot = nitroApp.chatBot;
  if (chatBot) {
    if (githubEvent === "issue_comment" || githubEvent === "pull_request_review_comment") {
      const handler = chatBot.webhooks.github;
      if (handler) {
        let chatResponse;
        try {
          chatResponse = await handler(request.clone(), {
            waitUntil: (promise) => {
              promise.catch((err) => log.error("waitUntil rejected:", err));
            }
          });
        } catch (err) {
          log.error("chat SDK threw \u2014 falling through to orchestrator:", err);
          chatResponse = new Response(null, { status: 500 });
        }
        if (chatResponse.ok) {
          orchestrator.triggerRefresh();
          let body2;
          try {
            body2 = await chatResponse.json();
          } catch (parseErr) {
            log.warn("failed to parse chat SDK response body:", parseErr);
            body2 = { accepted: true };
          }
          setResponseStatus(event, chatResponse.status);
          return body2;
        }
      }
    }
  }
  if (githubEvent === "issue_comment" && secret) {
    try {
      const payload = await request.clone().json();
      const githubChannel = config.channels.find((c) => {
        const platform = config.platforms[c.platform];
        return (platform == null ? void 0 : platform.kind) === "github";
      });
      const rawGithubPlatform = githubChannel ? config.platforms[githubChannel.platform] : void 0;
      const githubPlatform = (rawGithubPlatform == null ? void 0 : rawGithubPlatform.kind) === "github" ? rawGithubPlatform : void 0;
      const botUsername = (githubPlatform == null ? void 0 : githubPlatform.bot_username) || process.env.GITHUB_BOT_USERNAME || "agent-please";
      const allowedAssociations = githubChannel == null ? void 0 : githubChannel.allowed_associations;
      if (shouldHandleComment(payload, botUsername, allowedAssociations)) {
        const token = githubPlatform == null ? void 0 : githubPlatform.api_key;
        if (!token) {
          log.warn(`no API token available for issue comment handler \u2014 platforms.github.api_key is required for comment dispatch (platform: ${(_b = githubChannel == null ? void 0 : githubChannel.platform) != null ? _b : "github"})`);
          setResponseStatus(event, 503);
          return { error: { code: "no_token", message: "No API token configured for issue comment dispatch" } };
        }
        const apiEndpoint = (_d = (_c = config.projects.find((p) => {
          var _a2;
          return ((_a2 = config.platforms[p.platform]) == null ? void 0 : _a2.kind) === "github";
        })) == null ? void 0 : _c.endpoint) != null ? _d : "https://api.github.com";
        const github = createGitHubRestApi(token, apiEndpoint);
        const workflow = orchestrator.getWorkflow();
        const dispatchLockAdapter = useNitroApp().chatStateAdapter;
        handleIssueCommentMention(payload, {
          config,
          workflow,
          github,
          dispatchLockAdapter
        }).catch((err) => log.error("issue comment handler error:", err));
        setResponseStatus(event, 202);
        return { accepted: true, handler: "issue_comment_agent" };
      }
    } catch (err) {
      log.error("failed to parse issue_comment payload for agent dispatch:", err);
      setResponseStatus(event, 400);
      return { error: { code: "invalid_payload", message: "Failed to parse issue_comment payload" } };
    }
  }
  const verify = secret ? getVerifier(secret) : null;
  const response = await handleWebhook(
    request,
    verify,
    events,
    () => orchestrator.triggerRefresh()
  );
  const body = await response.json();
  setResponseStatus(event, response.status);
  for (const [key, value] of response.headers.entries()) {
    setResponseHeader(event, key, value);
  }
  return body;
});

export { github_post as default };
//# sourceMappingURL=github.post.mjs.map
