#!/usr/bin/env bun
import { TelegramBot } from './telegram-bot.ts';
import { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

interface Config {
  botToken: string;
  allowedUsers: string[];
  zcodeCliXPath: string;
}

async function loadConfig(): Promise<Config> {
  const envPath = join(process.cwd(), '.env');
  const envContent = readFileSync(envPath, 'utf-8');

  const config: Config = {
    botToken: '',
    allowedUsers: [],
    zcodeCliXPath: process.cwd(),
  };

  for (const line of envContent.split('\n')) {
    const trimmed = line.trim();
    if (trimmed.startsWith('TELEGRAM_BOT_TOKEN=')) {
      config.botToken = trimmed.replace('TELEGRAM_BOT_TOKEN=', '').trim();
    } else if (trimmed.startsWith('TELEGRAM_ALLOWED_USERS=')) {
      config.allowedUsers = trimmed
        .replace('TELEGRAM_ALLOWED_USERS=', '')
        .split(',')
        .map((u) => u.trim());
    } else if (trimmed.startsWith('ZCODE_CLI_X_PATH=')) {
      config.zcodeCliXPath = trimmed.replace('ZCODE_CLI_X_PATH=', '').trim();
    }
  }

  if (!config.botToken) {
    throw new Error('TELEGRAM_BOT_TOKEN not found in .env file');
  }

  return config;
}

async function main() {
  console.log('🚀 zCode CLI X - Telegram Integration');
  console.log('='.repeat(50));

  try {
    const config = await loadConfig();

    console.log('✓ Configuration loaded');
    console.log(`  Bot Token: ${config.botToken.substring(0, 10)}...`);
    console.log(`  Allowed Users: ${config.allowedUsers.join(', ')}`);
    console.log(`  zCode CLI X Path: ${config.zcodeCliXPath}`);

    const bot = new TelegramBot({
      botToken: config.botToken,
      allowedUsers: config.allowedUsers,
      zcodeCliXPath: config.zcodeCliXPath,
    });

    console.log('\n🤖 Starting Telegram bot...');
    console.log('Press Ctrl+C to stop\n');

    await bot.startPolling();

    // Handle graceful shutdown
    process.on('SIGINT', async () => {
      console.log('\n\n🛑 Shutting down Telegram bot...');
      bot.stop();
      process.exit(0);
    });

  } catch (error) {
    console.error('❌ Fatal error:', error);
    process.exit(1);
  }
}

main();
