// /server/game/logic/tauntLogic.js
const GAME_CONFIG = require('../../core/config'); // Путь к config.js
// Вам понадобится доступ к gameData.tauntSystem здесь.
// Либо импортируйте весь gameData, либо только tauntSystem из data/taunts.js
const gameData = require('../../data'); // Импортируем собранный gameData из data/index.js

/**
 * Получает случайную насмешку из системы насмешек.
 * (Ваша существующая функция getRandomTaunt)
 */
function getRandomTaunt(speakerCharacterKey, trigger, context = {}, configToUse, opponentFullData, currentGameState) {
    // Проверяем наличие системы насмешек для говорящего персонажа
    const speakerTauntSystem = gameData.tauntSystem?.[speakerCharacterKey]; // Используем gameData.tauntSystem
    if (!speakerTauntSystem) return "(Молчание)";

    const opponentCharacterKey = opponentFullData?.baseStats?.characterKey || currentGameState?.opponent?.characterKey; // Получаем ключ оппонента
    if (!opponentCharacterKey) { // Если оппонент не определен (например, начало игры с AI, где оппонент еще не fully в gameState)
        // console.warn(`getRandomTaunt: Opponent character key not determined for speaker ${speakerCharacterKey}, trigger ${trigger}`);
        // Можно попробовать определить оппонента по-другому или вернуть общую фразу / молчание
        if (trigger === 'battleStart' && speakerCharacterKey === 'elena' && currentGameState.gameMode === 'ai') {
            // Для Елены против AI Баларда в начале боя
            const balardTaunts = speakerTauntSystem.balard;
            if (balardTaunts?.onBattleState?.start) {
                const potentialTaunts = balardTaunts.onBattleState.start;
                return potentialTaunts[Math.floor(Math.random() * potentialTaunts.length)] || "(Молчание)";
            }
        }
        return "(Молчание)";
    }


    const tauntBranch = speakerTauntSystem[opponentCharacterKey];
    if (!tauntBranch) {
        return "(Молчание)";
    }

    let potentialTaunts = [];

    if (trigger === 'battleStart') {
        potentialTaunts = tauntBranch.onBattleState?.start;
    } else if (trigger === 'opponentNearDefeatCheck') {
        const opponentState = currentGameState?.player?.characterKey === opponentCharacterKey ? currentGameState.player : currentGameState.opponent;
        if (opponentState && opponentState.maxHp > 0 && opponentState.currentHp / opponentState.maxHp < 0.20) {
            potentialTaunts = tauntBranch.onBattleState?.opponentNearDefeat;
        }
    } else if (trigger === 'selfCastAbility' && context.abilityId) {
        potentialTaunts = tauntBranch.selfCastAbility?.[context.abilityId];
    } else if (trigger === 'basicAttack' && tauntBranch.basicAttack) {
        const opponentState = currentGameState?.player?.characterKey === opponentCharacterKey ? currentGameState.player : currentGameState.opponent;
        if (speakerCharacterKey === 'elena' && opponentCharacterKey === 'balard' && opponentState) {
            const opponentHpPerc = (opponentState.currentHp / opponentState.maxHp) * 100;
            if (opponentHpPerc <= configToUse.PLAYER_MERCY_TAUNT_THRESHOLD_PERCENT) {
                potentialTaunts = tauntBranch.basicAttack.dominating;
            } else {
                potentialTaunts = tauntBranch.basicAttack.merciful;
            }
        } else {
            potentialTaunts = tauntBranch.basicAttack.general || []; // Фоллбэк на пустой массив
        }
    } else if (trigger === 'onOpponentAction' && context.abilityId) {
        const actionResponses = tauntBranch.onOpponentAction?.[context.abilityId];
        if (actionResponses) {
            if (typeof actionResponses === 'object' && !Array.isArray(actionResponses) && context.outcome && context.outcome in actionResponses) {
                potentialTaunts = actionResponses[context.outcome];
            } else if (Array.isArray(actionResponses)) {
                potentialTaunts = actionResponses;
            }
        }
    } else if (trigger === 'onOpponentAttackBlocked' && tauntBranch.onOpponentAction?.attackBlocked) {
        potentialTaunts = tauntBranch.onOpponentAction.attackBlocked;
    } else if (trigger === 'onOpponentAttackHit' && tauntBranch.onOpponentAction?.attackHits) {
        potentialTaunts = tauntBranch.onOpponentAction.attackHits;
    }

    if (!Array.isArray(potentialTaunts) || potentialTaunts.length === 0) {
        // Фоллбэк на общие фразы при basicAttack, если специфичные не найдены
        if (trigger === 'basicAttack' && tauntBranch.basicAttack?.general && tauntBranch.basicAttack.general.length > 0) {
            potentialTaunts = tauntBranch.basicAttack.general;
        } else {
            return "(Молчание)";
        }
    }

    const selectedTaunt = potentialTaunts[Math.floor(Math.random() * potentialTaunts.length)];
    return selectedTaunt || "(Молчание)";
}

module.exports = {
    getRandomTaunt
};