import { AuroraClient } from "@/lib/BotClient";
import { env } from "@shared/lib/env";
import { join } from "node:path";
import { initializeConfig } from "@shared/lib/config";
import { registerDomainEventListeners } from "@shared/lib/eventWiring";
import { gameRegistry } from "@shared/games/registry";
import { chessPlugin } from "@shared/games/chess/plugin";

import { startWebServerFromRoot } from "../api/src/server";

// Register game plugins
gameRegistry.register(chessPlugin);

// Initialize config from database
await initializeConfig();

// Register domain event listeners before loading commands/events
registerDomainEventListeners();

// Load commands & events
await AuroraClient.loadCommands();
await AuroraClient.loadEvents();
await AuroraClient.deployCommands();
await AuroraClient.setupSystemEvents();

console.log("🌐 Starting web server...");

let shuttingDown = false;

const webProjectPath = join(import.meta.dir, "../api");
const webPort = Number(process.env.WEB_PORT) || 3000;
const webHost = process.env.HOST || "0.0.0.0";

// Start web server in the same process
const webServer = await startWebServerFromRoot(webProjectPath, {
    port: webPort,
    hostname: webHost,
});

// login with the token from .env
if (!env.DISCORD_BOT_TOKEN) {
    throw new Error("❌ DISCORD_BOT_TOKEN is not set in environment variables.");
}
AuroraClient.login(env.DISCORD_BOT_TOKEN);

// Handle graceful shutdown
const shutdownHandler = async () => {
    if (shuttingDown) return;
    shuttingDown = true;
    console.log("🛑 Shutdown signal received. Stopping services...");

    // Stop web server
    await webServer.stop();

    // Stop bot
    AuroraClient.shutdown();

    process.exit(0);
};

process.on("SIGINT", shutdownHandler);
process.on("SIGTERM", shutdownHandler);