import { Shoukaku, NodeOption, ShoukakuOptions, Player, Connectors } from 'shoukaku';
import logger from '../utils/logger.js';
import { BotClient } from '../index.js';
// Removed imports from play.ts for now as player listeners are removed

// Define Node options (replace with your actual Lavalink details from .env)
const nodes: NodeOption[] = [
    {
        name: process.env.LAVALINK_NAME || 'Lavalink-Node-1',
        url: process.env.LAVALINK_URL || 'lavalink:2333', // Use service name for Docker Compose if applicable
        auth: process.env.LAVALINK_AUTH || 'youshallnotpass',
        secure: process.env.LAVALINK_SECURE === 'true' || false,
    },
];

// Define Shoukaku options
const shoukakuOptions: ShoukakuOptions = {
    moveOnDisconnect: false,
    resume: false, // Resume doesn't work reliably across restarts/disconnects without session persistence
    reconnectTries: 3,
    reconnectInterval: 5, // In seconds
    restTimeout: 15000, // In milliseconds
    voiceConnectionTimeout: 15, // In seconds
};

// Function to initialize Shoukaku and attach listeners
export function initializeShoukaku(client: BotClient): Shoukaku {
    if (!client) {
        throw new Error("initializeShoukaku requires a client instance.");
    }

    const shoukaku = new Shoukaku(new Connectors.DiscordJS(client), nodes, shoukakuOptions);

    // --- Shoukaku Node Event Listeners ---
    shoukaku.on('ready', (name, resumed) =>
        logger.info(`Lavalink Node '${name}' ready. Resumed: ${resumed}`)
    );

    shoukaku.on('error', (name, error) =>
        logger.error(`Lavalink Node '${name}' error: ${error.message}`, error)
    );

    shoukaku.on('close', (name, code, reason) =>
        logger.warn(`Lavalink Node '${name}' closed. Code: ${code}. Reason: ${reason || 'No reason'}`)
    );

    // Fix: Correct disconnect listener signature
    shoukaku.on('disconnect', (name, count) => {
        // count = count of players disconnected from the node
        logger.warn(`Lavalink Node '${name}' disconnected. ${count} players disconnected.`);
        // If players were not moved, you might want to attempt to reconnect them or clean them up.
    });

    shoukaku.on('debug', (name, info) => {
        // Only log debug messages if not in production or if explicitly enabled
        if (process.env.NODE_ENV !== 'production' || process.env.LAVALINK_DEBUG === 'true') {
             logger.debug(`Lavalink Node '${name}' debug: ${info}`);
        }
    });

    // --- Shoukaku Player Event Listeners ---
    // REMOVED - These need to be attached differently in Shoukaku v4 (e.g., when player is created)

    logger.info("Shoukaku instance created and node event listeners attached.");
    return shoukaku;
}
