'use strict';
const { Bot } = require('grammy');
const ChannelBase = require('./channel-base');
const eventBus = require('../events/event-bus');

class TelegramChannel extends ChannelBase {
  constructor(opts = {}) {
    super('telegram');
    this.botToken = opts.botToken || process.env.TELEGRAM_BOT_TOKEN || null;
    this.ownerChatId = opts.ownerChatId ? Number(opts.ownerChatId) : null;
    this._onMessage = opts.onMessage || null;
    this._bot = null;
  }

  async start() {
    if (!this.botToken) {
      console.log('[telegram] No bot token configured, skipping');
      return;
    }

    this._bot = new Bot(this.botToken);

    // Setup helper — tells the user their chat ID for config
    this._bot.command('whoami', (ctx) => {
      ctx.reply(`Your chat ID: ${ctx.from.id}`);
    });

    // Text message handler
    this._bot.on('message:text', async (ctx) => {
      const senderId = ctx.from.id;
      const text = ctx.message.text;

      // Owner-only gate (both should be Numbers, but coerce for safety)
      if (this.ownerChatId && Number(senderId) !== Number(this.ownerChatId)) {
        await ctx.reply('This is a private assistant.');
        return;
      }

      console.log(`[telegram] Message from ${senderId}: ${text.slice(0, 50)}...`);
      eventBus.emitMessage('telegram', text, String(senderId));

      if (this._onMessage) {
        try {
          const response = await this._onMessage(text, String(senderId));
          if (response) {
            // Telegram has a 4096 char limit per message — split if needed
            const MAX_LEN = 4096;
            if (response.length <= MAX_LEN) {
              await ctx.reply(response);
            } else {
              for (let i = 0; i < response.length; i += MAX_LEN) {
                await ctx.reply(response.slice(i, i + MAX_LEN));
              }
            }
          }
        } catch (err) {
          console.error('[telegram] onMessage error:', err.message);
          await ctx.reply('Sorry, something went wrong processing your message.');
        }
      }
    });

    // Error handler
    this._bot.catch((err) => {
      console.error('[telegram] Bot error:', err.message);
    });

    // Start long polling (non-blocking)
    this._bot.start({
      onStart: () => {
        this.running = true;
        console.log('[telegram] Bot started (long polling)');
      },
    });
  }

  async stop() {
    this.running = false;
    if (this._bot) {
      await this._bot.stop();
      console.log('[telegram] Bot stopped');
    }
  }

  async send(chatId, message) {
    if (!this._bot) return;
    try {
      await this._bot.api.sendMessage(chatId, message);
      console.log(`[telegram] Sent message to ${chatId}`);
    } catch (err) {
      console.error('[telegram] Send error:', err.message);
    }
  }
}

module.exports = TelegramChannel;
