using System;
using System.IO;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
namespace RynthCore.Plugin.RynthAi.Loot;
/// What the rule that takes an item says to do with it, for the inventory commands.
internal enum InventoryRuleKind { None, Keep, Salvage, Other }
///
/// A loot profile read for a command that judges what the character carries (2026-12-01 command
/// audit: /ub equip load|test and /ub autosalvage), not for looting: a VTank .utl or RynthAi's own
/// .json, read once for the command. Loading one never changes the loot profile in use.
///
internal sealed class InventoryRules
{
private readonly VTankLootProfile? _utl;
private readonly LootProfile? _json;
/// The file it came from.
public string Path { get; }
public string FileName => System.IO.Path.GetFileName(Path);
public int RuleCount => _utl?.Rules.Count ?? _json?.Rules.Count ?? 0;
private InventoryRules(string path, VTankLootProfile? utl, LootProfile? json)
{
Path = path;
_utl = utl;
_json = json;
}
/// The profile at , or null with why not.
public static InventoryRules? Load(string path, out string error)
{
error = string.Empty;
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
{
error = "not found";
return null;
}
try
{
return path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
? new InventoryRules(path, null, LootProfile.Load(path))
: new InventoryRules(path, VTankLootParser.Load(path), null);
}
catch (Exception ex)
{
error = ex.Message;
return null;
}
}
/// For tests: rules already in memory.
internal static InventoryRules From(string path, VTankLootProfile profile) => new(path, profile, null);
///
/// The first rule that takes , as the looter decides it
/// (): when a rule
/// that could take it needs the item's identify data and is false.
/// A native .json profile needs no ID to decide.
///
public VTankLootVerdict Decide(WorldObject item, VTankLootContext? ctx, CharacterSkills? skills, bool hasIdData,
out InventoryRuleKind kind, out string ruleName)
{
kind = InventoryRuleKind.None;
ruleName = string.Empty;
if (_utl != null)
{
VTankLootVerdict v = VTankLootEvaluator.Decide(_utl, item, ctx, hasIdData, out int index);
if (index >= 0)
{
VTankLootRule rule = _utl.Rules[index];
ruleName = LootWhy.NameOf(rule, index);
kind = rule.Action switch
{
VTankLootAction.Keep or VTankLootAction.KeepUpTo => InventoryRuleKind.Keep,
VTankLootAction.Salvage => InventoryRuleKind.Salvage,
_ => InventoryRuleKind.Other,
};
}
return v;
}
if (_json != null)
{
var (action, rule) = LootEvaluator.Classify(_json, item, skills);
if (rule == null) return VTankLootVerdict.NoMatch;
ruleName = string.IsNullOrWhiteSpace(rule.Name) ? "rule" : rule.Name.Trim();
kind = action switch
{
LootAction.Keep or LootAction.KeepUpTo => InventoryRuleKind.Keep,
LootAction.Salvage => InventoryRuleKind.Salvage,
_ => InventoryRuleKind.Other,
};
return VTankLootVerdict.Match;
}
return VTankLootVerdict.NoMatch;
}
}