import { Client } from '@heroiclabs/nakama-js';
import WebSocket from 'ws';
import { v4 as uuidv4 } from 'uuid';

// Polyfill WebSocket for Node.js
global.WebSocket = WebSocket as any;

const startBot = async (idx: number) => {
  const client = new Client('defaultkey', 'localhost', '7350', false);
  const deviceId = `bot-player-${idx}-${uuidv4()}`;
  
  try {
    const session = await client.authenticateDevice(deviceId, true, `Bot-${idx}`);
    console.log(`[Bot ${idx}] Authenticated: ${session.user_id}`);
    
    const socket = client.createSocket(false, false);
    await socket.connect(session, true);
    console.log(`[Bot ${idx}] Socket Connected`);
    
    // Use matchmaker to find existing matches
    socket.onmatchmakermatched = async (matched) => {
      console.log(`[Bot ${idx}] Matchmaker Matched:`, matched);
      
      const matchId = matched.match_id || (matched as any).matchId;
      const token = matched.token;

      if (matchId) {
        console.log(`[Bot ${idx}] Joining Match ID: ${matchId}`);
        const match = await socket.joinMatch(matchId, token);
        console.log(`[Bot ${idx}] Joined Match: ${match.match_id}`);
      } else {
        console.error(`[Bot ${idx}] Match ID missing in matched data`);
      }
    };

    // Start Matchmaking - this will find existing matches
    console.log(`[Bot ${idx}] Joining Matchmaker...`);
    await socket.addMatchmaker('*', 4, 4);

  } catch (err) {
    console.error(`[Bot ${idx}] Error:`, err);
  }
};

// Start 3 Bots
console.log('Starting 3 Bots to fill the match...');
for (let i = 1; i <= 3; i++) {
  startBot(i);
}

// Keep script running
setInterval(() => {}, 10000);