//
// Created by sebastian on 02.08.26.
//

#include "LudoAiController.h"

#include <iostream>
#include <ostream>
#include <utility>

#include "gameMode/LudoRules.h"

ludo::LudoAiController::LudoAiController(std::shared_ptr<LudoGameMode> gameMode, engine::PlayerID player) : m_gameMode(std::move(gameMode)), m_player(player){
}

void ludo::LudoAiController::update(float deltaTime) {
    if (m_gameMode->getCurrentPlayer() != m_player) {
        m_thinkTimer = 0.0f;
        return;
    }

    m_thinkTimer += deltaTime;

    if (m_thinkTimer < kThinkDelay) return;
    std::cout << "Thinking done" << std::endl;
    m_thinkTimer = 0.0f;

    switch (m_gameMode->getState().getPhase()) {
        case TurnPhase::AwaitingRoll:
            m_gameMode->sendCommand(RollDiceCommand{m_player});
            break;
        case TurnPhase::AwaitingPieceSelection:
            if (auto pieceIndex = chooseMove()) {
                m_gameMode->sendCommand(MovePieceCommand{m_player, *pieceIndex});
            }
            break;
    }
}

std::optional<int> ludo::LudoAiController::chooseMove() const {
    auto color = m_gameMode->getColorOf(m_player);
    auto moveable = LudoRules::getMoveablePieceIndices(m_gameMode->getState(), color, m_gameMode->getState().getDiceValue());
    if (moveable.empty()) return std::nullopt;

    int diceValue = m_gameMode->getState().getDiceValue();

    //Priority 1: Schmeißen
    for (int idx : moveable) {
        if (LudoRules::wouldCapture(m_gameMode->getState(), idx, diceValue).has_value()) {
            return idx;
        }
    }
    for (int idx : moveable) {
        if (m_gameMode->getState().getPieces()[idx].state == PieceState::AtHome) return idx;
    }
    // Fallback: erste bewegbare Figur
    return moveable.front();
}
