export function parseIntegrationIssueCommand(commandBody) {
    const normalized = commandBody.trim();
    if (!normalized.toLowerCase().startsWith("/issue"))
        return null;
    const rawPayload = normalized.slice("/issue".length).trim();
    if (!rawPayload)
        return null;
    const [titleLine, ...bodyLines] = rawPayload.split(/\r?\n/);
    const title = titleLine?.trim();
    if (!title)
        return null;
    const body = bodyLines.join("\n").trim();
    return { title, body: body || null };
}
export function parseFeishuQuickCommand(commandBody) {
    const [command] = commandBody.trim().toLowerCase().split(/\s+/, 1);
    if (isRepeatedSlashCommand(command, "/new"))
        return { kind: "new" };
    if (isRepeatedSlashCommand(command, "/stop"))
        return { kind: "stop" };
    return null;
}
function isRepeatedSlashCommand(input, command) {
    if (!input)
        return false;
    let remaining = input;
    let count = 0;
    while (remaining.startsWith(command)) {
        count += 1;
        remaining = remaining.slice(command.length);
    }
    return count > 0 && remaining.length === 0;
}
export async function dispatchFeishuInboundMessage(event, deps) {
    const integration = await deps.resolveActiveIntegration(event);
    if (!integration || integration.status !== "active") {
        await auditDrop(deps, event, null, "revoked_installation");
        return { status: "dropped", reason: "revoked_installation" };
    }
    if (event.chatType === "group" && !event.addressedToBot) {
        await auditDrop(deps, event, integration, "not_addressed_in_group");
        return { status: "dropped", reason: "not_addressed_in_group" };
    }
    if (event.messageType !== "text") {
        await auditDrop(deps, event, integration, "unsupported_message_type");
        return { status: "dropped", reason: "unsupported_message_type" };
    }
    const binding = await deps.resolveUserBinding(integration, event);
    if (!binding) {
        const bindingToken = await deps.mintBindingToken(integration, event);
        await auditDrop(deps, event, integration, "unbound_user");
        return {
            status: "binding_required",
            bindingToken,
            outbound: createBindingRequiredResponse(event, bindingToken),
        };
    }
    if (!binding.orgMember) {
        await auditDrop(deps, event, integration, "non_org_member");
        return { status: "dropped", reason: "non_org_member" };
    }
    const dedupInserted = await deps.tryInsertDedup(integration, event);
    if (!dedupInserted) {
        await auditDrop(deps, event, integration, "duplicate");
        return { status: "dropped", reason: "duplicate" };
    }
    const chat = await deps.ensureChatBinding(integration, binding, event);
    const quickCommand = parseFeishuQuickCommand(event.commandBody);
    if (quickCommand && deps.handleQuickCommand) {
        const handled = await deps.handleQuickCommand(integration, binding, chat, quickCommand, event);
        return {
            status: "quick_command",
            command: handled.command,
            conversationId: handled.conversationId,
            chatMessageId: handled.chatMessageId,
            runId: handled.runId,
            outbound: {
                provider: event.provider,
                externalChatId: event.chatId,
                externalMessageId: null,
                text: handled.text,
            },
        };
    }
    const message = await deps.appendInboundMessage(integration, binding, chat, event);
    const command = parseIntegrationIssueCommand(event.commandBody);
    const issue = command && deps.createIssueFromCommand
        ? await deps.createIssueFromCommand(integration, binding, chat, message, command, event)
        : null;
    const run = deps.enqueueAgentRun
        ? await deps.enqueueAgentRun(integration, binding, chat, message, event, issue)
        : null;
    if (deps.createOutboundPlaceholder) {
        await deps.createOutboundPlaceholder(integration, chat, event, message, issue, run);
    }
    return {
        status: "accepted",
        conversationId: chat.conversationId,
        chatMessageId: message.chatMessageId,
        issueId: issue?.issueId ?? null,
        runId: run?.runId ?? null,
        outbound: createAcceptedResponse(event, issue, run),
    };
}
function createBindingRequiredResponse(event, bindingToken) {
    return {
        provider: event.provider,
        externalChatId: event.chatId,
        externalMessageId: null,
        text: [
            "请先绑定 Rudder 账号后再和这个 Agent 对话。",
            `绑定口令：${bindingToken.token}`,
            "口令 15 分钟内有效。绑定完成后请重新发送消息。",
        ].join("\n"),
    };
}
function createAcceptedResponse(event, issue, run) {
    const details = [
        issue ? `issue=${issue.issueId}` : null,
        run ? `run=${run.runId}` : null,
    ].filter(Boolean);
    return {
        provider: event.provider,
        externalChatId: event.chatId,
        externalMessageId: null,
        text: details.length > 0
            ? `已写入 Rudder Messenger，并开始处理（${details.join(", ")}）。`
            : "已写入 Rudder Messenger，并开始处理。",
    };
}
async function auditDrop(deps, event, integration, dropReason) {
    await deps.auditDrop({
        orgId: integration?.orgId ?? null,
        integrationId: integration?.id ?? null,
        provider: event.provider,
        externalChatId: event.chatId || null,
        externalChatType: event.chatType || null,
        externalEventId: event.eventId || null,
        externalMessageId: event.messageId || null,
        senderOpenId: event.senderOpenId || null,
        dropReason,
        bodyPersisted: false,
        metadata: null,
    });
}
//# sourceMappingURL=inbound-dispatcher.js.map