'use strict';

// Require log-web early to capture all console output from other modules
const LogWeb = require('./log-web');

const {sleep} = require('../utils');
const conf = require('../conf');
const {CJbot} = require('../model/minecraft');

const commands = require('./commands');

CJbot.pluginAdd(require('./swing'));
CJbot.pluginAdd(require('./craft'));
CJbot.pluginAdd(require('./tp'));
CJbot.pluginAdd(require('./ai'));
CJbot.pluginAdd(require('./guardianFarm'));
CJbot.pluginAdd(require('./goldFarm'));
CJbot.pluginAdd(require('./storage'));
CJbot.pluginAdd(require('./auto-eat'));
CJbot.pluginAdd(require('./farm-supply'));

for(let name in conf.mc.bots){
	if(CJbot.bots[name]) continue;
	let bot = new CJbot({name, host: conf.mc.host, ...conf.mc.bots[name]});
	CJbot.bots[name] = bot;

	for(let command of conf.mc.bots[name].commands || ['default']){
		for(let [name, toAdd] of Object.entries(commands[command])){
			bot.addCommand(name, toAdd)
		}
	}
}

// Initialize storage database early so web read-only routes work even with bots offline
const Database = require('./storage/database');
if (!Database.db) {
	Database.initialize(conf.storage.dbPath || './storage/storage.db')
		.then(async () => {
			console.log('Early DB initialization complete');
			// Seed invite sites from config after DB is ready
			if (conf.invite && conf.invite.seedSites) {
				await Database.seedInviteSites(conf.invite.seedSites);
				console.log('Invite sites seeded');
			}
		})
		.catch(err => console.error('Failed to initialize storage DB:', err));
}

// Start app-level web server (always available, even before bots connect)
const webServer = require('./web-server');
const ActivityWeb = require('./activity-web');
const ChatWeb = require('./chat-web');
const InvitePlugin = require('./invite');
webServer.queuePlugin(ChatWeb);
webServer.queuePlugin(ActivityWeb);
webServer.queuePlugin(LogWeb);
webServer.queuePlugin(InvitePlugin);
webServer.start().catch(err => console.error('Failed to start web server:', err));

(async ()=>{try{
	for(let name in CJbot.bots){
		let bot = CJbot.bots[name];
		if(bot.autoConnect){
			console.log('Trying to connect', name)
			console.log('Status for', name, await bot.connect());

			// bot.bot.setControlState('jump', true);
			// await sleep(5000);
			// bot.bot.setControlState('jump', false);
			await sleep(30000);
		}
	}
}catch(e){
	console.log('!!!!!!!! error:', e)
}})()


// module.exports = {bot: ez, henry, owen, linda, jimin, nova, ez};
