/**
 * test_connect.js -- Verify Mineflayer can connect to the dev Paper server.
 *
 * Usage: node test_connect.js [host] [port]
 * Defaults: 192.168.0.244 25568
 */

const mineflayer = require('mineflayer');

const host = process.argv[2] || '192.168.0.244';
const port = parseInt(process.argv[3] || '25568', 10);

console.log(`Connecting to ${host}:${port} as TestBot...`);

const bot = mineflayer.createBot({
  host,
  port,
  username: 'TestBot',
  auth: 'offline',
  version: '1.21.11',
});

bot.on('login', () => {
  console.log(`[OK] Logged in as ${bot.username}`);
});

bot.on('spawn', () => {
  const pos = bot.entity.position;
  console.log(`[OK] Spawned at x=${pos.x.toFixed(1)} y=${pos.y.toFixed(1)} z=${pos.z.toFixed(1)}`);
  console.log(`[OK] Gamemode: ${bot.game.gameMode}`);
  console.log(`[OK] Health: ${bot.health}, Food: ${bot.food}`);

  // Look around and report nearby blocks
  const block = bot.blockAt(bot.entity.position.offset(0, -1, 0));
  console.log(`[OK] Block below: ${block ? block.name : 'unknown'}`);

  // List nearby entities
  const entities = Object.values(bot.entities).filter(e => e !== bot.entity);
  console.log(`[OK] Nearby entities: ${entities.length}`);

  console.log('\n=== Connection test passed ===');
  console.log('Disconnecting in 3s...');
  setTimeout(() => {
    bot.quit('Test complete');
    process.exit(0);
  }, 3000);
});

bot.on('chat', (username, message) => {
  console.log(`[CHAT] <${username}> ${message}`);
});

bot.on('error', (err) => {
  console.error(`[ERROR] ${err.message}`);
  process.exit(1);
});

bot.on('kicked', (reason) => {
  console.error(`[KICKED] ${reason}`);
  process.exit(1);
});

bot.on('end', (reason) => {
  console.log(`[END] ${reason}`);
});

// Timeout if connection takes too long
setTimeout(() => {
  console.error('[TIMEOUT] Connection took longer than 30s');
  process.exit(1);
}, 30000);
