import 'dart:math';
import '../enums.dart';
import '../models.dart';
import '../config.dart';
import 'combat_calculator.dart';

class EnemyAIService {
  /// Decides the next action for the enemy based on status effects and probability.
  static EnemyIntent generateIntent(Character enemy, Random random) {
    if (enemy.isDead) {
      return EnemyIntent(
        type: EnemyActionType.attack,
        value: 0,
        risk: RiskLevel.safe,
        description: "Dead",
        isSuccess: false,
        finalValue: 0,
      );
    }

    // Decide Action Type
    bool canDefend =
        enemy.baseDefense > 0 &&
        !enemy.hasStatus(StatusEffectType.defenseForbidden);
    
    bool isAttack = true; // Default to attack

    if (canDefend) {
      // Both options available or forced? Currently using probability from config.
      isAttack = random.nextDouble() < BattleConfig.enemyAttackChance;
    } else {
      // Must attack if defense is forbidden or base defense is 0
      isAttack = true;
    }

    // Decide Risk Level
    RiskLevel risk = RiskLevel.values[random.nextInt(RiskLevel.values.length)];

    CombatResult result;
    if (isAttack) {
      result = CombatCalculator.calculateActionOutcome(
        actionType: ActionType.attack,
        risk: risk,
        luck: enemy.totalLuck,
        baseValue: enemy.totalAtk,
      );

      return EnemyIntent(
        type: EnemyActionType.attack,
        value: result.value,
        risk: risk,
        description: "${result.value} (${risk.name})",
        isSuccess: result.success,
        finalValue: result.value,
      );
    } else {
      result = CombatCalculator.calculateActionOutcome(
        actionType: ActionType.defend,
        risk: risk,
        luck: enemy.totalLuck,
        baseValue: enemy.totalDefense,
      );

      return EnemyIntent(
        type: EnemyActionType.defend,
        value: result.value,
        risk: risk,
        description: "${result.value} (${risk.name})",
        isSuccess: result.success,
        finalValue: result.value,
      );
    }
  }
}
