using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Loot;
///
/// A slayer weapon's damage bonus as its appraisal text gives it (2026-11-27).
///
/// ACE never sends SlayerDamageBonus (float 138) in an appraisal: the property isn't an assessment
/// property, so a loot rule's "Slayer damage bonus at least 1.01" read 0 on every weapon and never
/// matched. Servers built on ACECustom write the bonus into the weapon's text instead
/// ("- Shadow Slayer: 1.5x Damage"). The loot readers (RynthAi's WorldObject and LootItemFacts) fall
/// back to that text for key 138 when no value was sent; a value the server does send still wins.
/// Where no server writes the line the bonus stays unreadable: the slayer type (int 166) is the test
/// that works everywhere ().
///
/// Spotted by SilentKelpie (Forgejo rynth PR #12); re-implemented here.
///
public static class SlayerText
{
/// SlayerDamageBonus (STypeFloat 138).
public const int SlayerDamageBonusKey = 138;
/// SlayerCreatureType (STypeInt 166), the test every ACE server answers.
public const int SlayerTypeKey = 166;
/// What the Loot Editor says about a rule that tests the bonus.
public const string Hint =
"Slayer damage bonus can only be read on servers that write it in the item text (\"Shadow Slayer: 1.5x Damage\"); elsewhere use Slayer type.";
// "- Shadow Slayer: 1.5x Damage", "Olthoi Slayer: 2x". One line each; the dash is optional.
private static readonly Regex Line = new(@"^[ \t]*-?[ \t]*(?[^\r\n:]+?)[ \t]+Slayer:[ \t]*(?\d+(?:\.\d+)?)[ \t]*x",
RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
/// The best "<creature> Slayer: N.Nx" multiplier in the texts (1.5 for "1.5x"), or 0 when none says one.
public static double BonusOf(params string?[] texts)
{
double best = 0;
foreach (string? t in texts)
{
if (string.IsNullOrEmpty(t) || t.IndexOf("Slayer", StringComparison.OrdinalIgnoreCase) < 0) continue;
foreach (Match m in Line.Matches(t))
if (double.TryParse(m.Groups["x"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out double x) && x > best)
best = x;
}
return best;
}
///
/// Key 138's value for a loot rule: the sent value when there is one (above 0), else the text's.
/// Any other key: unchanged.
///
public static double Resolve(int key, double sent, Func texts)
{
if (key != SlayerDamageBonusKey || sent > 0) return sent;
double x = BonusOf(texts());
return x > 0 ? x : sent;
}
}