//! The enemy brain, shared with combat-web's arena: fire the signature move on
//! a spaced-out coin flip, otherwise swing. Lives game-side, not in core, so
//! the engine stays policy-free.

use combat_core::ability::Ability;
use combat_core::controller::{Action, Controller, View};
use combat_core::rng::Rng;

#[derive(Debug, Default)]
pub struct MonsterAI;

impl MonsterAI {
    fn usable(view: &View, ab: &Ability) -> bool {
        ab.cost.fill <= view.me.vigor && !view.me.on_cooldown(&ab.id, view.tick)
    }
}

impl Controller for MonsterAI {
    fn decide(&mut self, view: &View, rng: &mut Rng) -> Action {
        let Some(target) = view.weakest_enemy() else {
            return Action::Idle;
        };

        // Signature move: priciest usable hostile ability that isn't the free
        // auto-attack, used on a coin-flip so big hits space into a readable duel.
        let use_signature = rng.chance_bp(5500);
        let signature = view
            .me
            .loadout
            .iter()
            .filter(|a| a.is_offensive() && a.cost.fill > 0 && Self::usable(view, a))
            .max_by_key(|a| a.cost.fill);
        if let (true, Some(ab)) = (use_signature, signature) {
            return Action::Use {
                ability_id: ab.id.clone(),
                targets: vec![target.id],
            };
        }

        let auto = view
            .me
            .loadout
            .iter()
            .filter(|a| a.is_offensive())
            .min_by_key(|a| a.cost.fill);
        match auto {
            Some(ab) if Self::usable(view, ab) => Action::Use {
                ability_id: ab.id.clone(),
                targets: vec![target.id],
            },
            _ => Action::Idle,
        }
    }

    fn label(&self) -> &str {
        "monster"
    }
}
