package com.jsjdesigns.poker

import com.jsjdesigns.poker.bot.BotProfile
import com.jsjdesigns.poker.bot.PersonaCue
import com.jsjdesigns.poker.bot.PersonaCueId
import com.jsjdesigns.poker.bot.TableTalkLine
import com.jsjdesigns.poker.game.TableSnapshot

/**
 * Builds the language-only cue from an already-applied public action.
 *
 * Accepting [TableSnapshot] here is safe because the richer engine type stops at
 * this function. [PersonaCue] is the only value that crosses into narration.
 */
fun personaCueFor(
    snapshot: TableSnapshot,
    profilesBySeat: Map<Int, BotProfile>,
    heroSeat: Int = HERO_SEAT,
): PersonaCue? {
    if (snapshot.phase != TableSnapshot.Phase.BETTING) return null
    val event = snapshot.lastAction ?: return null
    if (event.seat == heroSeat || event.street != snapshot.street) return null
    if (snapshot.actionNumber <= 0) return null
    val profile = profilesBySeat[event.seat] ?: return null
    val speaker = snapshot.seats.firstOrNull { it.index == event.seat } ?: return null

    return PersonaCue(
        id = PersonaCueId(snapshot.handNumber, snapshot.actionNumber),
        street = snapshot.street,
        speakerSeat = event.seat,
        speakerName = event.name,
        persona = profile.persona,
        actionType = event.action.type,
        amount = event.action.amount,
        pot = snapshot.pot,
        isAllIn = speaker.allIn,
        activePlayers = snapshot.activeSeats.size,
    )
}

fun UiState.acceptsTableTalk(line: TableTalkLine): Boolean {
    val snap = snapshot ?: return false
    return snap.phase == TableSnapshot.Phase.BETTING &&
        snap.handNumber == line.cueId.handNumber &&
        snap.actionNumber == line.cueId.actionNumber &&
        snap.street == line.street
}

fun UiState.visibleTableTalk(): TableTalkLine? =
    tableTalk.takeIf { it != null && acceptsTableTalk(it) }
