// Discord bot — minimal, fast. Reuses svc registry from bot/index.js
import { Client, GatewayIntentBits, Partials } from 'discord.js';
import { logger } from '../utils/logger.js';
import { registerChannel } from './delivery-hub.js';

const INTENTS = GatewayIntentBits.GuildMessages | GatewayIntentBits.MessageContent |
  GatewayIntentBits.DirectMessages;
const PARTIALS = [Partials.Channel];

export async function initDiscord(token, svc, chatWithAI) {
  if (!token) { logger.warn('⚠ Discord token not set'); return null; }

  const client = new Client({ intents: INTENTS, partials: PARTIALS, 
    makeCache: (manager) => ['UserManager', 'ChannelManager'].includes(manager.constructor.name) ? manager : false,
  });

  client.once('ready', () => {
    logger.info('✅ Discord bot connected');
    registerChannel('discord', async (msg) => {
      // broadcast to first available guild channel
      const guild = client.guilds.cache.first();
      if (!guild) return;
      const ch = guild.systemChannel || guild.channels.cache.find(c => c.type === 0);
      if (ch) await ch.send(msg.slice(0, 1900));
    });
  });

  client.on('messageCreate', async (msg) => {
    if (msg.author.bot) return;
    // Ignore commands directed at other bots
    if (msg.mentions.has(client.user) || msg.channel.type === 1) {
      const text = msg.content.replace(/<@!?\d+>/g, '').trim() || 'hello';
      await msg.channel.sendTyping();
      const result = await chatWithAI([
        { role: 'system', content: `You are zCode CLI X on Discord. Be concise.` },
        { role: 'user', content: text },
      ]);
      await msg.reply(typeof result === 'string' ? result.slice(0, 1900) : result);
    }
  });

  await client.login(token);
  return client;
}
