import { ShardingManager } from 'discord.js';
import path from 'path';
import { config } from 'dotenv';
import { existsSync } from 'fs';
import * as grpc from '@grpc/grpc-js';
import { kordProto } from '@kord/grpc-contracts';

const envPath = path.resolve(process.cwd(), '../../.env');
if (existsSync(envPath)) {
  config({ path: envPath });
} else {
  // Fallback for direct execution from root
  config({ path: path.resolve(process.cwd(), '.env') });
}

if (!process.env.DISCORD_TOKEN) {
  console.error('❌ DISCORD_TOKEN is missing in shard manager! Current CWD:', process.cwd());
}

const manager = new ShardingManager(path.resolve(__dirname, 'index.ts'), {
  token: process.env.DISCORD_TOKEN,
  execArgv: ['--import', 'tsx'], // Node.js v22 compatibility
});

manager.on('shardCreate', (shard) => {
  console.log(`Launched shard ${shard.id}`);
  
  shard.on('ready', () => {
    console.log(`Shard ${shard.id} is ready`);
  });

  shard.on('disconnect', () => {
    console.warn(`Shard ${shard.id} disconnected`);
  });

  shard.on('reconnecting', () => {
    console.warn(`Shard ${shard.id} reconnecting`);
  });
});

import { startGrpcServer } from './utils/grpcServer';

// ... (existing env/manager setup)

// --- gRPC Proxy Server Setup ---
// We start the gRPC server early to ensure the dashboard can connect
// even if Discord sharding takes time to initialize.
startGrpcServer(manager as any);

// Only spawn shards after gRPC server is successfully bound
console.log('Starting Discord ShardingManager...');
manager.spawn().catch(err => {
  console.error('Failed to spawn shards:', err);
});

