using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Server.Data; using Server.Data.Entities; using Server.Networking; using Server.Networking.Messages; using System.Text.Json; namespace Server.Game.Dungeon; /// /// Handles crafting operations including recipe discovery, crafting, and skill progression /// public class CraftingHandler { private readonly ILogger _log; private readonly IServiceScopeFactory _scopeFactory; // Cache recipes in memory for fast lookup private Dictionary _recipes = new(); private Dictionary _ingredientHashToRecipeId = new(); // For recipe discovery private bool _recipesLoaded = false; public CraftingHandler(ILogger log, IServiceScopeFactory scopeFactory) { _log = log; _scopeFactory = scopeFactory; } public async Task InitializeAsync() { using var scope = _scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var recipes = await db.DungeonCraftingRecipes .Include(r => r.Ingredients) .Where(r => r.IsEnabled) .ToListAsync(); _recipes = recipes.ToDictionary(r => r.Id); // Build ingredient hash lookup for recipe discovery foreach (var recipe in recipes) { var hash = GetIngredientHash(recipe.Ingredients.ToList()); _ingredientHashToRecipeId[hash] = recipe.Id; _log.LogDebug("Recipe {Name} (ID {Id}) hash: {Hash}", recipe.Name, recipe.Id, hash); } _recipesLoaded = true; _log.LogInformation("CraftingHandler loaded {Count} recipes", recipes.Count); } /// /// Get crafting skill for a character, creating if it doesn't exist /// public async Task GetOrCreateCraftingSkillAsync( GameDbContext db, ulong characterId, CraftingSkillType skillType) { var skill = await db.DungeonCharacterCraftingSkills .FirstOrDefaultAsync(s => s.CharacterId == characterId && s.SkillType == skillType); if (skill == null) { skill = new DungeonCharacterCraftingSkill { CharacterId = characterId, SkillType = skillType, Level = 1, Experience = 0 }; db.DungeonCharacterCraftingSkills.Add(skill); await db.SaveChangesAsync(); } return skill; } /// /// Get all crafting skills for a character /// public async Task> GetAllCraftingSkillsAsync( GameDbContext db, ulong characterId) { var skills = await db.DungeonCharacterCraftingSkills .Where(s => s.CharacterId == characterId) .ToListAsync(); var result = new Dictionary(); // Ensure all skill types exist foreach (CraftingSkillType skillType in Enum.GetValues(typeof(CraftingSkillType))) { var skill = skills.FirstOrDefault(s => s.SkillType == skillType); if (skill == null) { skill = new DungeonCharacterCraftingSkill { CharacterId = characterId, SkillType = skillType, Level = 1, Experience = 0 }; db.DungeonCharacterCraftingSkills.Add(skill); } result[skillType] = skill; } await db.SaveChangesAsync(); return result; } /// /// Get known recipes for a character /// public async Task> GetKnownRecipesAsync(GameDbContext db, ulong characterId) { // Get explicitly known recipes var knownRecipeIds = await db.DungeonCharacterKnownRecipes .Where(kr => kr.CharacterId == characterId) .Select(kr => kr.RecipeId) .ToListAsync(); // Also include base recipes that everyone knows var baseRecipeIds = _recipes.Values .Where(r => r.IsBaseRecipe) .Select(r => r.Id); var allKnownIds = knownRecipeIds.Union(baseRecipeIds).ToHashSet(); return _recipes.Values.Where(r => allKnownIds.Contains(r.Id)).ToList(); } /// /// Try to discover a recipe by combining ingredients /// Returns the recipe if discovered, null otherwise /// public async Task<(DungeonCraftingRecipe? Recipe, bool AlreadyKnown, string? Error)> TryDiscoverRecipeAsync( GameDbContext db, ulong characterId, List<(int ItemDefinitionId, int Quantity)> ingredients, CraftingSkillType? skillTypeFilter = null) { // Build hash from ingredients var sortedIngredients = ingredients.OrderBy(i => i.ItemDefinitionId).ThenBy(i => i.Quantity).ToList(); var hash = GetIngredientHashFromInput(sortedIngredients); _log.LogInformation("Discovery attempt - Hash: {Hash}, SkillFilter: {Skill}, Ingredients: {Ing}", hash, skillTypeFilter, string.Join(", ", ingredients.Select(i => $"{i.ItemDefinitionId}x{i.Quantity}"))); if (!_ingredientHashToRecipeId.TryGetValue(hash, out var recipeId)) { _log.LogInformation("No recipe found for hash {Hash}. Known hashes: {Hashes}", hash, string.Join(", ", _ingredientHashToRecipeId.Keys.Take(10))); return (null, false, "No recipe found for these ingredients"); } var recipe = _recipes[recipeId]; // Check skill type filter if (skillTypeFilter.HasValue && recipe.SkillType != skillTypeFilter.Value) { return (null, false, $"This combination creates something in {recipe.SkillType}, not {skillTypeFilter.Value}"); } // Check if already known var alreadyKnown = await db.DungeonCharacterKnownRecipes .AnyAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId); if (alreadyKnown) { return (recipe, true, null); } // Learn the recipe db.DungeonCharacterKnownRecipes.Add(new DungeonCharacterKnownRecipe { CharacterId = characterId, RecipeId = recipeId, DiscoveredAt = DateTime.UtcNow }); await db.SaveChangesAsync(); _log.LogInformation("Character {CharId} discovered recipe: {Recipe}", characterId, recipe.Name); return (recipe, false, null); } /// /// Consume materials on failed discovery attempt (65% chance to lose materials) /// public async Task<(bool MaterialsLost, List LostItems)> TryConsumeMaterialsOnFailedDiscoveryAsync( GameDbContext db, ulong characterId, List<(int ItemDefinitionId, int Quantity)> ingredients) { const float MATERIAL_LOSS_CHANCE = 0.65f; var rng = new Random(); if (rng.NextDouble() >= MATERIAL_LOSS_CHANCE) { // Lucky! Materials saved return (false, new List()); } // Load inventory var inventory = await db.DungeonCharacterItems .Where(i => i.CharacterId == characterId && !i.IsEquipped) .ToListAsync(); var lostItems = new List(); foreach (var (itemDefId, qty) in ingredients) { int remaining = qty; var stacks = inventory.Where(i => i.ItemDefinitionId == itemDefId).ToList(); foreach (var stack in stacks) { if (remaining <= 0) break; int toRemove = Math.Min(remaining, stack.Quantity); stack.Quantity -= toRemove; remaining -= toRemove; if (stack.Quantity <= 0) { db.DungeonCharacterItems.Remove(stack); } } // Get item name for message var itemDef = await db.DungeonItemDefinitions.FindAsync(itemDefId); if (itemDef != null) { lostItems.Add($"{qty}x {itemDef.Name}"); } } await db.SaveChangesAsync(); _log.LogInformation("Character {CharId} lost materials on failed discovery: {Items}", characterId, string.Join(", ", lostItems)); return (true, lostItems); } /// /// Craft an item from a known recipe /// public async Task CraftItemAsync( GameDbContext db, ulong characterId, int recipeId, DungeonCharacter character) { if (!_recipes.TryGetValue(recipeId, out var recipe)) { return new CraftingResult { Success = false, ErrorMessage = "Recipe not found" }; } // Verify character knows the recipe var isBaseRecipe = recipe.IsBaseRecipe; var knowsRecipe = isBaseRecipe || await db.DungeonCharacterKnownRecipes .AnyAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId); if (!knowsRecipe) { return new CraftingResult { Success = false, ErrorMessage = "You don't know this recipe" }; } // Get crafting skill var skill = await GetOrCreateCraftingSkillAsync(db, characterId, recipe.SkillType); // Check level requirement if (skill.Level < recipe.RequiredLevel) { return new CraftingResult { Success = false, ErrorMessage = $"Requires {recipe.SkillType} level {recipe.RequiredLevel}" }; } // Verify ingredients var inventory = await db.DungeonCharacterItems .Where(i => i.CharacterId == characterId && !i.IsEquipped) .ToListAsync(); var ingredientsToConsume = new List<(DungeonCharacterItem Item, int ConsumeCount)>(); foreach (var ingredient in recipe.Ingredients) { var availableItems = inventory .Where(i => i.ItemDefinitionId == ingredient.ItemDefinitionId) .ToList(); int totalAvailable = availableItems.Sum(i => i.Quantity); if (totalAvailable < ingredient.Quantity) { var itemDef = await db.DungeonItemDefinitions.FindAsync(ingredient.ItemDefinitionId); return new CraftingResult { Success = false, ErrorMessage = $"Need {ingredient.Quantity} {itemDef?.Name ?? "items"} (have {totalAvailable})" }; } // Mark items to consume int remaining = ingredient.Quantity; foreach (var item in availableItems) { if (remaining <= 0) break; int toConsume = Math.Min(remaining, item.Quantity); ingredientsToConsume.Add((item, toConsume)); remaining -= toConsume; } } // Consume ingredients foreach (var (item, consumeCount) in ingredientsToConsume) { item.Quantity -= consumeCount; if (item.Quantity <= 0) { db.DungeonCharacterItems.Remove(item); } } // Create output item var outputItemDef = await db.DungeonItemDefinitions.FindAsync(recipe.OutputItemDefinitionId); if (outputItemDef == null) { return new CraftingResult { Success = false, ErrorMessage = "Invalid recipe output" }; } // Check for bonus output (upgraded item at higher levels) bool gotBonusOutput = false; int finalOutputItemId = recipe.OutputItemDefinitionId; int finalOutputQuantity = recipe.OutputQuantity; if (recipe.BonusOutputItemDefinitionId.HasValue && skill.Level >= recipe.BonusOutputMinLevel) { // Calculate bonus chance based on level // At BonusOutputMinLevel: BonusOutputChanceAtMinLevel% chance // At BonusOutputMaxLevel: 100% chance // Linear interpolation between float levelRange = recipe.BonusOutputMaxLevel - recipe.BonusOutputMinLevel; float levelProgress = Math.Min(1f, (skill.Level - recipe.BonusOutputMinLevel) / Math.Max(1f, levelRange)); float bonusChance = recipe.BonusOutputChanceAtMinLevel + (100f - recipe.BonusOutputChanceAtMinLevel) * levelProgress; var rng = new Random(); if (rng.NextDouble() * 100 < bonusChance) { gotBonusOutput = true; finalOutputItemId = recipe.BonusOutputItemDefinitionId.Value; finalOutputQuantity = recipe.BonusOutputQuantity; outputItemDef = await db.DungeonItemDefinitions.FindAsync(finalOutputItemId); _log.LogInformation("Character {CharId} got bonus output! {BonusChance:F1}% chance", characterId, bonusChance); } } DungeonCraftedItem? craftedItem = null; var rollResults = new List<(string Stat, int Value)>(); // Handle stat rolling for equipment if (recipe.HasStatRolls && recipe.PossibleStats.Count > 0) { var rng = new Random(); craftedItem = new DungeonCraftedItem { BaseItemDefinitionId = finalOutputItemId, CrafterId = characterId, CrafterName = character.Name, RecipeId = recipeId, CraftedAt = DateTime.UtcNow, CraftingLevelAtCreation = skill.Level }; // Roll stats int rollCount = skill.StatRollCount; int minRoll = skill.MinStatRoll; int maxRoll = skill.MaxStatRoll; int totalRolled = 0; int maxPossibleTotal = 0; for (int i = 0; i < rollCount; i++) { var stat = recipe.PossibleStats[rng.Next(recipe.PossibleStats.Count)]; int value = rng.Next(minRoll, maxRoll + 1); totalRolled += value; maxPossibleTotal += maxRoll; ApplyStatRoll(craftedItem, stat, value); rollResults.Add((stat, value)); } // Calculate quality rating (0-100 based on how good the rolls were) craftedItem.QualityRating = maxPossibleTotal > 0 ? (int)(100f * totalRolled / maxPossibleTotal) : 50; craftedItem.RollHistoryJson = JsonSerializer.Serialize(rollResults.Select(r => new { stat = r.Stat, value = r.Value })); db.DungeonCraftedItems.Add(craftedItem); } // Check if we can stack with existing items (only for non-crafted items without stat rolls) int finalSlotIndex = -1; bool addedToStack = false; if (!recipe.HasStatRolls && outputItemDef != null && outputItemDef.Stackable) { // Find existing stack of same item var existingStack = inventory.FirstOrDefault(i => i.ItemDefinitionId == finalOutputItemId && !i.IsEquipped && i.Quantity < (outputItemDef.MaxStack > 0 ? outputItemDef.MaxStack : 99)); if (existingStack != null) { int canAdd = (outputItemDef.MaxStack > 0 ? outputItemDef.MaxStack : 99) - existingStack.Quantity; int toAdd = Math.Min(canAdd, finalOutputQuantity); existingStack.Quantity += toAdd; finalSlotIndex = existingStack.SlotIndex; addedToStack = true; // If we couldn't add all, we need a new slot for the rest if (toAdd < finalOutputQuantity) { finalOutputQuantity -= toAdd; addedToStack = false; // Need to create new item for remainder } else { finalOutputQuantity = 0; } } } // If not stacked (or remainder), find empty slot and create new item if (!addedToStack || finalOutputQuantity > 0) { var usedSlots = inventory.Where(i => i.CharacterId == characterId && !i.IsEquipped).Select(i => i.SlotIndex).ToHashSet(); int emptySlot = -1; for (int i = 0; i < 30; i++) { if (!usedSlots.Contains(i)) { emptySlot = i; break; } } if (emptySlot == -1 && finalOutputQuantity > 0) { return new CraftingResult { Success = false, ErrorMessage = "Inventory full" }; } if (finalOutputQuantity > 0) { var newItem = new DungeonCharacterItem { CharacterId = characterId, ItemDefinitionId = finalOutputItemId, Quantity = finalOutputQuantity, SlotIndex = emptySlot, IsEquipped = false, AcquiredAt = DateTime.UtcNow }; db.DungeonCharacterItems.Add(newItem); finalSlotIndex = emptySlot; // Link crafted item if applicable if (craftedItem != null) { await db.SaveChangesAsync(); // Save to get newItem.Id db.DungeonCharacterItemCraftedLinks.Add(new DungeonCharacterItemCraftedLink { CharacterItemId = newItem.Id, CraftedItemId = craftedItem.Id }); } } } await db.SaveChangesAsync(); // Award XP int xpGained = DungeonCharacterCraftingSkill.GetCraftingXp(recipe.Tier, skill.Level); skill.Experience += xpGained; skill.TotalItemsCrafted++; // Check for level up bool leveledUp = false; while (skill.Level < 100 && skill.Experience >= skill.ExperienceForNextLevel) { skill.Experience -= skill.ExperienceForNextLevel; skill.Level++; leveledUp = true; } // Update known recipe craft count var knownRecipe = await db.DungeonCharacterKnownRecipes .FirstOrDefaultAsync(kr => kr.CharacterId == characterId && kr.RecipeId == recipeId); if (knownRecipe != null) { knownRecipe.TimesCrafted++; } await db.SaveChangesAsync(); _log.LogInformation("Character {CharId} crafted {Item} (quality {Quality}, +{Xp} XP)", characterId, outputItemDef.Name, craftedItem?.QualityRating ?? 0, xpGained); return new CraftingResult { Success = true, OutputItem = outputItemDef, CraftedItem = craftedItem, RollResults = rollResults, XpGained = xpGained, NewSkillLevel = skill.Level, LeveledUp = leveledUp, SlotIndex = finalSlotIndex, GotBonusOutput = gotBonusOutput, OutputQuantity = recipe.OutputQuantity, AddedToStack = addedToStack }; } private void ApplyStatRoll(DungeonCraftedItem item, string stat, int value) { switch (stat) { case "BonusStrength": item.RolledBonusStrength += value; break; case "BonusIntelligence": item.RolledBonusIntelligence += value; break; case "BonusWisdom": item.RolledBonusWisdom += value; break; case "BonusEndurance": item.RolledBonusEndurance += value; break; case "BonusDexterity": item.RolledBonusDexterity += value; break; case "BonusHealth": item.RolledBonusHealth += value; break; case "BonusMana": item.RolledBonusMana += value; break; case "Armor": item.RolledBonusArmor += value; break; case "MagicResist": item.RolledBonusMagicResist += value; break; case "MinDamage": item.RolledBonusMinDamage += value; break; case "MaxDamage": item.RolledBonusMaxDamage += value; break; case "HealAmount": item.RolledBonusHealAmount += value; break; case "ManaRestore": item.RolledBonusManaRestore += value; break; } } private string GetIngredientHash(List ingredients) { var parts = ingredients .OrderBy(i => i.ItemDefinitionId) .ThenBy(i => i.Quantity) .Select(i => $"{i.ItemDefinitionId}:{i.Quantity}"); return string.Join("|", parts); } private string GetIngredientHashFromInput(List<(int ItemDefinitionId, int Quantity)> ingredients) { var parts = ingredients .OrderBy(i => i.ItemDefinitionId) .ThenBy(i => i.Quantity) .Select(i => $"{i.ItemDefinitionId}:{i.Quantity}"); return string.Join("|", parts); } } public class CraftingResult { public bool Success { get; set; } public string? ErrorMessage { get; set; } public DungeonItemDefinition? OutputItem { get; set; } public DungeonCraftedItem? CraftedItem { get; set; } public List<(string Stat, int Value)> RollResults { get; set; } = new(); public int XpGained { get; set; } public int NewSkillLevel { get; set; } public bool LeveledUp { get; set; } public int SlotIndex { get; set; } public bool GotBonusOutput { get; set; } public int OutputQuantity { get; set; } public bool AddedToStack { get; set; } }