import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/util/deterministic_random.dart';
import 'package:asciineverdie/src/core/util/pq_random.dart';

/// 스탯 관련 함수들
/// 원본 Main.pas의 스탯 처리 로직을 포팅

/// 스탯 증가 인덱스 결정 (원본 Main.pas:870-883)
int winStatIndex(DeterministicRandom rng, List<int> statValues) {
  // 50%: 모든 8개 스탯 중 랜덤
  // 50%: 첫 6개(STR~CHA)만 제곱 가중치로 선택
  if (rng.nextInt(2) == 0) {
    return rng.nextInt(statValues.length);
  }

  // 첫 6개(STR, CON, DEX, INT, WIS, CHA)만 제곱 가중치 적용
  const firstSixCount = 6;
  var total = 0;
  for (var i = 0; i < firstSixCount && i < statValues.length; i++) {
    total += statValues[i] * statValues[i];
  }
  if (total == 0) return rng.nextInt(firstSixCount);
  var pickValue = random64Below(rng, total);
  for (var i = 0; i < firstSixCount; i++) {
    pickValue -= statValues[i] * statValues[i];
    if (pickValue < 0) return i;
  }
  return firstSixCount - 1;
}

/// 스탯 증가 적용
Stats winStat(Stats stats, DeterministicRandom rng) {
  final values = <int>[
    stats.str,
    stats.con,
    stats.dex,
    stats.intelligence,
    stats.wis,
    stats.cha,
    stats.hpMax,
    stats.mpMax,
  ];
  final idx = winStatIndex(rng, values);
  switch (idx) {
    case 0:
      return stats.copyWith(str: stats.str + 1);
    case 1:
      return stats.copyWith(con: stats.con + 1);
    case 2:
      return stats.copyWith(dex: stats.dex + 1);
    case 3:
      return stats.copyWith(intelligence: stats.intelligence + 1);
    case 4:
      return stats.copyWith(wis: stats.wis + 1);
    case 5:
      return stats.copyWith(cha: stats.cha + 1);
    case 6:
      return stats.copyWith(hpMax: stats.hpMax + 1);
    case 7:
      return stats.copyWith(mpMax: stats.mpMax + 1);
    default:
      return stats;
  }
}
