import 'package:asciineverdie/src/core/engine/game_mutations.dart';
import 'package:asciineverdie/src/core/engine/potion_service.dart';
import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/monster_grade.dart';
import 'package:asciineverdie/src/core/model/potion.dart';

/// 전리품 처리 서비스
///
/// ProgressService에서 분리된 전리품 획득 로직 담당:
/// - 몬스터 부위 아이템 인벤토리 추가
/// - 특수 아이템 획득 (WinItem)
/// - 물약 드랍
class LootHandler {
  const LootHandler({required this.mutations});

  final GameMutations mutations;

  /// 킬 태스크 완료 시 전리품 획득 (원본 Main.pas:625-630)
  ({GameState state, Potion? droppedPotion}) winLoot(GameState state) {
    final taskInfo = state.progress.currentTask;
    final monsterPart = taskInfo.monsterPart ?? '';
    final monsterBaseName = taskInfo.monsterBaseName ?? '';

    var resultState = state;

    // 부위가 '*'이면 WinItem 호출 (특수 아이템)
    if (monsterPart == '*') {
      resultState = mutations.winItem(resultState);
    } else if (monsterPart.isNotEmpty && monsterBaseName.isNotEmpty) {
      // 원본: Add(Inventory, LowerCase(Split(fTask.Caption,1) + ' ' +
      //       ProperCase(Split(fTask.Caption,3))), 1);
      // 예: "goblin Claw" 형태로 인벤토리 추가
      final itemName =
          '${monsterBaseName.toLowerCase()} ${_properCase(monsterPart)}';

      // 인벤토리에 추가
      final items = [...resultState.inventory.items];
      final existing = items.indexWhere((e) => e.name == itemName);
      if (existing >= 0) {
        items[existing] = items[existing].copyWith(
          count: items[existing].count + 1,
        );
      } else {
        items.add(InventoryEntry(name: itemName, count: 1));
      }

      resultState = resultState.copyWith(
        inventory: resultState.inventory.copyWith(items: items),
      );
    }

    // 물약 드랍 시도
    final potionService = const PotionService();
    final rng = resultState.rng;
    final monsterLevel = taskInfo.monsterLevel ?? resultState.traits.level;
    final monsterGrade = taskInfo.monsterGrade ?? MonsterGrade.normal;
    final (updatedPotionInventory, droppedPotion) = potionService.tryPotionDrop(
      playerLevel: resultState.traits.level,
      monsterLevel: monsterLevel,
      monsterGrade: monsterGrade,
      inventory: resultState.potionInventory,
      roll: rng.nextInt(100),
      typeRoll: rng.nextInt(100),
    );

    return (
      state: resultState.copyWith(
        rng: rng,
        potionInventory: updatedPotionInventory,
      ),
      droppedPotion: droppedPotion,
    );
  }

  /// 첫 글자만 대문자로 변환 (원본 ProperCase)
  String _properCase(String s) {
    if (s.isEmpty) return s;
    return s[0].toUpperCase() + s.substring(1);
  }
}
