RemoveConditionBattleMutationInterceptor.kt

package io.github.lishangbu.avalon.game.battle.engine.core.runtime.flow

import io.github.lishangbu.avalon.game.battle.engine.core.constant.BattleAttributeKeys
import io.github.lishangbu.avalon.game.battle.engine.core.event.StandardHookNames
import io.github.lishangbu.avalon.game.battle.engine.core.model.SideState
import io.github.lishangbu.avalon.game.battle.engine.core.mutation.BattleMutation
import io.github.lishangbu.avalon.game.battle.engine.core.mutation.RemoveConditionMutation
import io.github.lishangbu.avalon.game.battle.engine.core.mutation.RemoveFieldConditionMutation
import io.github.lishangbu.avalon.game.battle.engine.core.mutation.RemoveSideConditionMutation
import io.github.lishangbu.avalon.game.battle.engine.core.runtime.support.MutationTargetSelectorResolver
import io.github.lishangbu.avalon.game.battle.engine.core.type.StandardTargetSelectorIds

/**
 * condition 移除 mutation 的生命周期拦截器。
 *
 * 设计意图:
 * - 统一覆盖单位 condition、side condition 与 field condition 的移除前生命周期;
 * - 避免 `remove_condition` 在 unit/side/field 三类目标上再次出现“动作能生成 mutation,但生命周期没接通”的断点;
 * - 对不同作用域保持同一 hook 名称,差异通过 attributes 暴露。
 */
class RemoveConditionBattleMutationInterceptor : BattleMutationInterceptor {
    override val order: Int = 500

    override fun supports(mutation: BattleMutation): Boolean = mutation is RemoveConditionMutation || mutation is RemoveSideConditionMutation || mutation is RemoveFieldConditionMutation

    override fun intercept(
        context: BattleMutationInterceptionContext,
        attachedEffectProcessor: BattleAttachedEffectProcessor,
    ): BattleMutationInterceptionResult =
        when (val mutation = context.mutation) {
            is RemoveConditionMutation -> interceptUnitCondition(context, mutation, attachedEffectProcessor)
            is RemoveSideConditionMutation -> interceptSideCondition(context, mutation, attachedEffectProcessor)
            is RemoveFieldConditionMutation -> interceptFieldCondition(context, mutation, attachedEffectProcessor)
            else -> BattleMutationInterceptionResult(context.snapshot, true, context.mutation)
        }

    private fun interceptUnitCondition(
        context: BattleMutationInterceptionContext,
        mutation: RemoveConditionMutation,
        attachedEffectProcessor: BattleAttachedEffectProcessor,
    ): BattleMutationInterceptionResult {
        val targetUnitIds =
            MutationTargetSelectorResolver.resolve(
                mutation.target,
                BattleMutationInterceptorSupport.mutationApplicationContext(context),
            )
        var currentSnapshot = context.snapshot
        var blocked = false

        targetUnitIds.forEach { affectedTargetId ->
            val affectedUnit = currentSnapshot.units[affectedTargetId] ?: return@forEach
            if (mutation.conditionEffectId !in affectedUnit.conditionStates) {
                return@forEach
            }
            val result =
                attachedEffectProcessor.process(
                    snapshot = currentSnapshot,
                    unitId = affectedTargetId,
                    hookName = StandardHookNames.ON_REMOVE_CONDITION.value,
                    targetId = affectedTargetId,
                    sourceId = context.sourceId,
                    relay = true,
                    attributes =
                        buildMap {
                            put("conditionEffectId", mutation.conditionEffectId)
                            put("conditionScope", UNIT_SCOPE)
                            BattleMutationInterceptorSupport
                                .resolveTargetRelation(currentSnapshot, context.sourceId, affectedTargetId)
                                ?.let { relation -> put(BattleAttributeKeys.TARGET_RELATION, relation) }
                        },
                )
            currentSnapshot = result.snapshot
            if (result.cancelled || result.relay == false) {
                blocked = true
            }
        }

        return BattleMutationInterceptionResult(
            snapshot = currentSnapshot,
            allowed = !blocked,
            mutation = mutation,
        )
    }

    private fun interceptSideCondition(
        context: BattleMutationInterceptionContext,
        mutation: RemoveSideConditionMutation,
        attachedEffectProcessor: BattleAttachedEffectProcessor,
    ): BattleMutationInterceptionResult {
        val targetSides = resolveTargetSides(context, mutation)
        var currentSnapshot = context.snapshot
        var blocked = false

        targetSides.forEach { targetSide ->
            val hasCondition = mutation.conditionEffectId in targetSide.conditionStates
            if (!hasCondition) {
                return@forEach
            }
            targetSide.activeUnitIds.distinct().forEach { affectedTargetId ->
                val result =
                    attachedEffectProcessor.process(
                        snapshot = currentSnapshot,
                        unitId = affectedTargetId,
                        hookName = StandardHookNames.ON_REMOVE_CONDITION.value,
                        targetId = affectedTargetId,
                        sourceId = context.sourceId,
                        relay = true,
                        attributes =
                            buildMap {
                                put("conditionEffectId", mutation.conditionEffectId)
                                put("conditionScope", SIDE_SCOPE)
                                put("sideId", targetSide.id)
                                BattleMutationInterceptorSupport
                                    .resolveTargetRelation(currentSnapshot, context.sourceId, affectedTargetId)
                                    ?.let { relation -> put(BattleAttributeKeys.TARGET_RELATION, relation) }
                            },
                    )
                currentSnapshot = result.snapshot
                if (result.cancelled || result.relay == false) {
                    blocked = true
                }
            }
        }

        return BattleMutationInterceptionResult(
            snapshot = currentSnapshot,
            allowed = !blocked,
            mutation = mutation,
        )
    }

    private fun interceptFieldCondition(
        context: BattleMutationInterceptionContext,
        mutation: RemoveFieldConditionMutation,
        attachedEffectProcessor: BattleAttachedEffectProcessor,
    ): BattleMutationInterceptionResult {
        if (mutation.conditionEffectId !in context.snapshot.field.conditionStates) {
            return BattleMutationInterceptionResult(context.snapshot, true, mutation)
        }
        val targetUnitIds =
            context.snapshot.sides.values
                .flatMap(SideState::activeUnitIds)
                .distinct()
        var currentSnapshot = context.snapshot
        var blocked = false

        targetUnitIds.forEach { affectedTargetId ->
            val result =
                attachedEffectProcessor.process(
                    snapshot = currentSnapshot,
                    unitId = affectedTargetId,
                    hookName = StandardHookNames.ON_REMOVE_CONDITION.value,
                    targetId = affectedTargetId,
                    sourceId = context.sourceId,
                    relay = true,
                    attributes =
                        buildMap {
                            put("conditionEffectId", mutation.conditionEffectId)
                            put("conditionScope", FIELD_SCOPE)
                            BattleMutationInterceptorSupport
                                .resolveTargetRelation(currentSnapshot, context.sourceId, affectedTargetId)
                                ?.let { relation -> put(BattleAttributeKeys.TARGET_RELATION, relation) }
                        },
                )
            currentSnapshot = result.snapshot
            if (result.cancelled || result.relay == false) {
                blocked = true
            }
        }

        return BattleMutationInterceptionResult(
            snapshot = currentSnapshot,
            allowed = !blocked,
            mutation = mutation,
        )
    }

    private fun resolveTargetSides(
        context: BattleMutationInterceptionContext,
        mutation: RemoveSideConditionMutation,
    ): List<SideState> =
        when (mutation.target) {
            StandardTargetSelectorIds.SIDE -> listOfNotNull(BattleMutationInterceptorSupport.mutationApplicationContext(context).side)
            StandardTargetSelectorIds.FOE_SIDE -> listOfNotNull(BattleMutationInterceptorSupport.mutationApplicationContext(context).foeSide)
            else -> emptyList()
        }

    private companion object {
        private const val UNIT_SCOPE: String = "unit"
        private const val SIDE_SCOPE: String = "side"
        private const val FIELD_SCOPE: String = "field"
    }
}