package com.ghost.technic.server.game;

import com.ghost.technic.server.Player;
import com.ghost.technic.server.card.effect.CardAbility;
import com.ghost.technic.server.card.effect.StartOfOpponentTurnAbility;
import com.ghost.technic.server.card.effect.StartOfTurnAbility;
import com.ghost.technic.server.card.playable.usable.impl.CreatureCard;
import com.ghost.technic.server.game.event.EventType;
import com.ghost.technic.server.game.event.GameEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class GameTurnManager {

    private final GameState gameState;
    private final GameActionService gameActionService;

    public void takeTurn(Player player) {
        log.info("== Turn {}: {} ==", gameState.getTurnCount() + 1, player.getName());

        // “Start of turn” effect(s) resolve.
        handleStartOfTurnAbilities(player);

        // Forge a key step
        gameActionService.forgeKey(player);

        // Choose which house will be the active house for this turn.
        gameActionService.chooseActiveHouse(player);
//        player.chooseHouse();

        // “After you choose a house” effects resolve.

        // STEP 3: PLAY, DISCARD, OR USE CARDS

        player.readyCards();

        player.drawCardsToSix();

        // “End of turn” effects resolve.
    }

    public void endOfTurn(Player player) {
        var endOfTurnGameEvent = new GameEvent(EventType.TURN_ENDS , Map.of("player", player));
        gameState.getEventBus().publish(endOfTurnGameEvent);
    }

    public void handleStartOfTurnAbilities(Player activePlayer) {
        List<CreatureCard> allCreatures = gameState.getAllCreaturesInPlay();

        for (CreatureCard creature : allCreatures) {
            for (CardAbility ability : creature.getAbilities()) {
                if (ability instanceof StartOfTurnAbility startOfTurnAbility) {
                    boolean isOwnedByActivePlayer = gameState.getOwnerOf(creature).equals(activePlayer);
                    boolean isOpponentAbility = !isOwnedByActivePlayer;

                    // Only trigger relevant abilities
                    if ((startOfTurnAbility instanceof StartOfOpponentTurnAbility && isOpponentAbility) ||
                            (!(startOfTurnAbility instanceof StartOfOpponentTurnAbility) && isOwnedByActivePlayer)) {
                        startOfTurnAbility.onStartOfTurn(gameActionService, activePlayer, creature);
                    }
                }
            }
        }
    }

}
