import { b as paths, f as secureFetch, g as vaultStore, h as saveConfig, m as loadConfig } from "./index.mjs";
import { c as We, d as Ct, i as Ne, l as Ze, r as Le, s as Ve, t as He, u as bt } from "./dist-BFgk1-yR.mjs";
import { existsSync, readFileSync, writeFileSync } from "node:fs";

//#region src/channels/connect-telegram.ts
function handleCancel() {
	Ne("Setup cancelled.");
	process.exit(0);
}
async function validateBotToken(token) {
	const body = await (await secureFetch(`https://api.telegram.org/bot${token}/getMe`)).json();
	if (!body.ok || !body.result) throw new Error("Invalid bot token: Telegram API rejected it");
	return body.result;
}
async function fetchBotPhoto(token, botId) {
	try {
		const photos = (await (await secureFetch(`https://api.telegram.org/bot${token}/getUserProfilePhotos?user_id=${String(botId)}&limit=1`)).json()).result?.photos;
		if (!photos?.[0]?.length) return null;
		const largest = photos[0].at(-1);
		if (!largest) return null;
		const fileBody = await (await secureFetch(`https://api.telegram.org/bot${token}/getFile?file_id=${largest.file_id}`)).json();
		if (!fileBody.result?.file_path) return null;
		return `https://api.telegram.org/file/bot${token}/${fileBody.result.file_path}`;
	} catch {
		return null;
	}
}
async function connectTelegram() {
	We("Connect Telegram");
	const token = await He({ message: "Enter your Telegram bot token (from @BotFather)" });
	if (Ct(token)) handleCancel();
	const s = bt();
	s.start("Validating token...");
	let botUser;
	try {
		botUser = await validateBotToken(token);
		s.stop(`Bot verified: @${botUser.username ?? botUser.first_name}`);
	} catch (error) {
		s.stop("Validation failed");
		Ne(error instanceof Error ? error.message : String(error));
		process.exit(1);
	}
	const userIdInput = await Ze({
		message: "Enter your Telegram user ID (numeric, from @userinfobot)",
		validate: (value) => {
			if (!value) return "Required";
			const parsed = parseInt(value, 10);
			if (Number.isNaN(parsed) || parsed <= 0) return "Must be a positive integer";
		}
	});
	if (Ct(userIdInput)) handleCancel();
	const userId = parseInt(userIdInput, 10);
	s.start("Storing credentials...");
	const nodeId = `telegram_${botUser.id}`;
	await vaultStore(`channel_token_${nodeId}`, token);
	let canvas = {
		nodes: [],
		edges: [],
		workspaces: []
	};
	if (existsSync(paths.canvas)) try {
		canvas = JSON.parse(readFileSync(paths.canvas, "utf-8"));
	} catch {
		canvas = {
			nodes: [],
			edges: [],
			workspaces: []
		};
	}
	const botUsername = botUser.username ?? botUser.first_name;
	const existingIdx = canvas.nodes.findIndex((n) => n.id === nodeId);
	const nodeData = {
		id: nodeId,
		platform: "telegram",
		label: `@${botUsername}`,
		photo: await fetchBotPhoto(token, botUser.id),
		position: {
			x: 200,
			y: 200
		},
		status: "connected",
		credentials: `channel_token_${nodeId}`,
		meta: {
			botId: String(botUser.id),
			userId: String(userId),
			firstName: botUser.first_name
		}
	};
	if (existingIdx >= 0) canvas.nodes[existingIdx] = {
		...canvas.nodes[existingIdx],
		...nodeData
	};
	else canvas.nodes.push(nodeData);
	writeFileSync(paths.canvas, JSON.stringify(canvas, null, 2), "utf-8");
	const config = await loadConfig();
	await saveConfig({
		...config,
		channels: {
			...config.channels,
			telegram: {
				...config.channels.telegram,
				enabled: true,
				allowedUserIds: [userId]
			}
		}
	});
	s.stop("Credentials stored in vault, canvas node created");
	Ve([
		`Bot: @${botUsername}`,
		`Node ID: ${nodeId}`,
		`Allowed user: ${String(userId)}`,
		`Voice transcription: ${config.channels.telegram.voice.enabled ? "enabled" : "disabled"}`,
		"",
		"Restart the daemon to activate:",
		"  sauria daemon"
	].join("\n"), "Telegram connected");
	Le("Done.");
}

//#endregion
export { connectTelegram };
//# sourceMappingURL=connect-telegram-VkF91smz.mjs.map