import { GmailEmailClient } from "../email/gmail-email.js";
import { logger } from "../logger.js";
/**
 * Resolve the Telegram bot's username from its token using the Bot API.
 */
async function resolveBotUsername(botToken) {
    try {
        const res = await fetch(`https://api.telegram.org/bot${botToken}/getMe`, {
            signal: AbortSignal.timeout(10_000),
        });
        const data = (await res.json());
        return data.ok ? (data.result?.username ?? null) : null;
    }
    catch (err) {
        logger.warn(`Failed to resolve Telegram bot username: ${err instanceof Error ? err.message : String(err)}`);
        return null;
    }
}
/**
 * Send the onboarding invitation email to the owner.
 * Includes a verification code and a direct link to the Telegram bot.
 */
export async function sendOnboardingEmail(config, ownerConfig) {
    const botToken = config.channels.telegram?.botToken;
    if (!botToken) {
        throw new Error("Telegram is not configured. Cannot send onboarding email without a Telegram bot.");
    }
    logger.debug("Resolving Telegram bot username...");
    const botUsername = await resolveBotUsername(botToken);
    if (!botUsername) {
        throw new Error("Could not resolve Telegram bot username. Check the bot token in config.json.");
    }
    logger.debug(`Bot username resolved: @${botUsername}`);
    const code = ownerConfig.onboardingCode;
    if (!code) {
        throw new Error("No onboarding code found in owner.json.");
    }
    const telegramLink = `https://t.me/${botUsername}?start=${code}`;
    const emailBody = `Hi ${ownerConfig.ownerName || "there"}!

I'm your new personal desktop assistant, and I'm ready to get started.

To complete setup, please click the link below to open Telegram and verify your identity:

${telegramLink}

That's it — once verified, I'll be ready to assist you right away.

If the link doesn't work, you can also open Telegram, search for @${botUsername}, and send:

   /start ${code}

If you don't have Telegram installed, you can get it at https://telegram.org

Looking forward to working with you!`;
    logger.debug(`Sending onboarding email to ${ownerConfig.ownerEmail}...`);
    const emailClient = new GmailEmailClient(config);
    await emailClient.sendEmail({
        to: ownerConfig.ownerEmail,
        subject: "Your Personal Assistant Is Ready - Let's Get Started!",
        body: emailBody,
    });
    logger.system(`Onboarding email sent to ${ownerConfig.ownerEmail} (bot: @${botUsername})`);
}
function buildWelcomeMessage(agentName, ownerName) {
    const heartbeatNote = "Other messages (e.g. WeChat, Feishu, WhatsApp...) are checked during wakeup cycles, " +
        "so there may be a noticeable delay if the heartbeat interval is large.";
    return (`Hi ${ownerName}!\n\n` +
        `I'm ${agentName}, your personal desktop assistant. ` +
        `Here are a few things to know about how I work:\n\n` +
        `1. I check Telegram and Gmail messages instantly — those are the fastest ways to reach me.\n\n` +
        `2. ${heartbeatNote}\n\n` +
        `3. I'll evolve over time — learning your preferences, priorities, and picking up new skills as we go.\n\n` +
        `4. I do my best to remember rules and important things you tell me, but my memory isn't perfect. ` +
        `Feel free to remind me if something slips.\n\n` +
        `5. I'm single-threaded: I can only handle one task at a time, but I can switch between tasks when needed.\n\n` +
        `I'm initializing and will be ready to assist you in a few minutes. \n` +
        `Looking forward to working with you!`);
}
/**
 * Send a welcome introduction to the owner via Telegram and Gmail
 * after onboarding is complete.
 */
export async function sendWelcomeMessages(config, ownerConfig, channelManager) {
    const agentName = config.agentName;
    const ownerName = ownerConfig.ownerName;
    const message = buildWelcomeMessage(agentName, ownerName);
    // Send via Telegram
    if (ownerConfig.telegramChatId) {
        try {
            await channelManager.sendMessage("telegram", String(ownerConfig.telegramChatId), message);
            logger.system("Welcome message sent via Telegram");
        }
        catch (err) {
            logger.warn(`Failed to send welcome message via Telegram: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    // Send via Gmail
    try {
        const emailClient = new GmailEmailClient(config);
        await emailClient.sendEmail({
            to: ownerConfig.ownerEmail,
            subject: `${agentName} — Nice to Meet You!`,
            body: message,
        });
        logger.system(`Welcome email sent to ${ownerConfig.ownerEmail}`);
    }
    catch (err) {
        logger.warn(`Failed to send welcome email: ${err instanceof Error ? err.message : String(err)}`);
    }
}
//# sourceMappingURL=send-invite.js.map