import { z } from "zod";
import { tool } from "@anthropic-ai/claude-agent-sdk";
import { getAgentState } from "../agent/state.js";
import { takeScreenshot } from "./screenshot.js";
export const notifyUserTool = tool("notify_user", "Send a message to the user through a messaging channel. Supports text and optional image/file attachments. Use this to communicate results, answer questions, request help, or send files.", {
    message: z
        .string()
        .describe("The text message to send to the user"),
    channel: z
        .string()
        .optional()
        .describe("Channel to send through (e.g. 'gmail', 'telegram', 'discord'). When replying to a specific message, always pass the channel it came from. Defaults to owner's Telegram."),
    to: z
        .string()
        .optional()
        .describe("Recipient identifier (email, chat ID, etc.). When replying to a specific message, always pass the sender. Defaults to the most recent sender on the resolved channel, or the owner."),
    image_url: z
        .string()
        .optional()
        .describe("URL of an image to send with the message"),
    image_path: z
        .string()
        .optional()
        .describe("Absolute local file path of an image to send (e.g. /tmp/resized.jpg)"),
    file_url: z
        .string()
        .optional()
        .describe("URL of a file to send with the message"),
    file_path: z
        .string()
        .optional()
        .describe("Absolute local file path of a file to send"),
    file_name: z
        .string()
        .optional()
        .describe("Display filename for the attached file"),
    attach_screenshot: z
        .boolean()
        .default(false)
        .describe("Should include screenshot if this message is related to GUI operations."),
}, async (args) => {
    const state = getAgentState();
    const { ownerConfig } = state;
    // Static owner fallback: telegram (via telegramChatId) → gmail (via ownerEmail)
    const ownerChannel = ownerConfig.telegramChatId ? "telegram" : "gmail";
    const ownerRecipient = ownerConfig.telegramChatId
        ? String(ownerConfig.telegramChatId)
        : ownerConfig.ownerEmail;
    // Resolve channel: explicit arg → owner's channel
    const channel = args.channel ?? ownerChannel;
    // Resolve exact threading context first. Avoid arbitrary same-channel
    // fallback: for group chats this can route replies to the wrong group.
    let replyTarget = args.to
        ? state.replyMap.get(`${channel}::${args.to}`)
        : undefined;
    if (!replyTarget && !args.to && state.currentTaskReplyTarget?.channel === channel) {
        replyTarget = state.currentTaskReplyTarget;
    }
    const groupLikeTaskTarget = state.currentTaskReplyTarget?.channel === channel && state.currentTaskReplyTarget.isGroupLike
        ? state.currentTaskReplyTarget
        : undefined;
    // Resolve recipient: explicit arg → exact/task reply target → owner recipient.
    // Never silently fall back from a Telegram group-originated task to owner DM.
    const to = args.to ?? replyTarget?.sender ?? (groupLikeTaskTarget ? undefined : ownerRecipient);
    if (!to) {
        return {
            content: [
                {
                    type: "text",
                    text: "Error: No recipient specified and no exact recent message sender to reply to.",
                },
            ],
            isError: true,
        };
    }
    // Build attachments array from optional params
    const attachments = [];
    if (args.attach_screenshot) {
        const { filePath } = await takeScreenshot();
        attachments.push({
            type: "image",
            localPath: filePath,
            mimeType: "image/png",
            filename: "screenshot.png",
        });
    }
    if (args.image_url) {
        attachments.push({
            type: "image",
            url: args.image_url,
            mimeType: "image/png",
        });
    }
    if (args.image_path) {
        attachments.push({
            type: "image",
            localPath: args.image_path,
            mimeType: "image/jpeg",
            filename: args.file_name ?? args.image_path.split("/").pop(),
        });
    }
    if (args.file_url) {
        attachments.push({
            type: "file",
            url: args.file_url,
            filename: args.file_name,
        });
    }
    if (args.file_path) {
        attachments.push({
            type: "file",
            localPath: args.file_path,
            filename: args.file_name ?? args.file_path.split("/").pop(),
        });
    }
    try {
        await state.channelManager.sendMessage(channel, to, args.message, attachments.length > 0 ? attachments : undefined, replyTarget?.replyContext);
        state.hasRepliedInCycle = true;
        const attNote = attachments.length > 0
            ? ` with ${attachments.length} attachment(s)`
            : "";
        return {
            content: [
                {
                    type: "text",
                    text: `Message sent via ${channel} to ${to}${attNote}.`,
                },
            ],
        };
    }
    catch (err) {
        return {
            content: [
                {
                    type: "text",
                    text: `Failed to send message via ${channel}: ${err instanceof Error ? err.message : String(err)}`,
                },
            ],
            isError: true,
        };
    }
});
//# sourceMappingURL=notify.js.map