import { Bot } from './bot.js';
import { Router } from './router.js';

const token = process.env.TELEGRAM_BOT_TOKEN;
const authorizedRaw = process.env.TELEGRAM_AUTHORIZED_USERS || '';
const channelUrl = process.env.CHANNEL_URL || 'http://127.0.0.1:7100';
const channelSecret = process.env.CHANNEL_SECRET || '';

if (!token) {
  console.error('[main] TELEGRAM_BOT_TOKEN is required');
  process.exit(1);
}

const authorizedUsers = authorizedRaw.split(',').map((s) => s.trim()).filter(Boolean);

if (authorizedUsers.length === 0) {
  console.warn('[main] Warning: TELEGRAM_AUTHORIZED_USERS is empty — bot will not respond to anyone');
}

console.log('[main] Starting Telegram bridge');
console.log(`[main] Channel URL: ${channelUrl}`);
console.log(
  `[main] Authorized users: ${authorizedUsers.length > 0 ? authorizedUsers.join(', ') : '(none)'}`
);

const bot = new Bot(token, authorizedUsers);
const router = new Router(bot, channelUrl, channelSecret);

router.start();

console.log('[main] Telegram bridge running, polling for messages...');

process.on('SIGTERM', () => {
  console.log('[main] Shutting down...');
  router.stop();
  bot.stop();
  process.exit(0);
});
