using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using RynthCore.Loot;
using RynthCore.Loot.VTank;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Loot;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi;
///
/// UtilityBelt commands that had no RynthAi equivalent (2026-09-28 parity pass,
/// names and syntax read from UtilityBelt.dll's CommandPattern/Usage attributes):
/// delay, count, date/dateutc, id, pos, vitae, portal/portalp, playsound,
/// setmotion/getmotion/clearmotion, autostack, autocram, opt, help, simplejump,
/// dumpskills, quests, translateroute.
///
public sealed partial class RynthAiPlugin
{
// ── /ub delay queue ─────────────────────────────────────────────────────
// FromMeta: the line was queued by a running meta, so it runs as one when due (it may be
// /mt vendor sell or /mt trade accept, which only act for a meta).
private readonly List<(long DueMs, string Command, bool FromMeta)> _delayedCommands = new();
/// Runs /ub delay commands that are due. Called every tick.
private void TickDelayedCommands()
{
// Out of world, OnChatBarEnter ignores the line and it went raw to AC's chat
// parser at character select. TeardownSession empties the queue at logout.
if (_delayedCommands.Count == 0 || !_loginComplete) return;
long now = Environment.TickCount64;
for (int i = 0; i < _delayedCommands.Count; i++)
{
if (_delayedCommands[i].DueMs > now) continue;
string cmd = _delayedCommands[i].Command;
bool fromMeta = _delayedCommands[i].FromMeta;
_delayedCommands.RemoveAt(i--);
try
{
if (fromMeta) RunAsMeta(() => { HandleRynthChatSubmit(cmd); return true; });
else HandleRynthChatSubmit(cmd);
}
catch (Exception ex) { Log($"[RynthAi] /ub delay: '{cmd}' threw {ex.Message}"); }
}
}
/// UB Util.Think: "/tell yourself, msg" so metas can watch for it; else a chat line.
private void UbSay(string msg, bool think)
{
if (think && Host.HasInvokeChatParser && _playerId != 0
&& Host.TryGetObjectName(_playerId, out string me) && !string.IsNullOrWhiteSpace(me))
{
Host.InvokeChatParser($"/tell {me}, {msg}");
Reply.Answered(); // the tell to yourself is the answer (metas watch for it)
return;
}
ChatLine("[RynthAi] " + msg);
}
/// Handles the commands above. Returns false for anything else.
internal bool TryHandleUbExtra(string cmd, string fullCommand)
{
int sp = fullCommand.IndexOf(' ');
string rest = sp > 0 ? fullCommand.Substring(sp + 1).Trim() : "";
// rest starts with the verb; args = everything after it
int sp2 = rest.IndexOf(' ');
string args = sp2 > 0 ? rest.Substring(sp2 + 1).Trim() : "";
switch (cmd)
{
case "delay": UbDelay(args); return true;
case "count": UbCount(args); return true;
case "date": UbDate(args, utc: false); return true;
case "dateutc": UbDate(args, utc: true); return true;
case "id": UbId(); return true;
case "pos": UbPos(); return true;
case "vitae": UbSay($"My vitae is {EvalExpr("vitae[]")}%", think: true); return true;
case "portal": UbPortal(args, partial: false); return true;
case "portalp": UbPortal(args, partial: true); return true;
case "playsound": UbPlaySound(args); return true;
case "setmotion": UbSetMotion(args); return true;
case "getmotion": UbGetMotion(); return true;
case "clearmotion": EvalExpr("clearmotion[]"); ReplyOk("[RynthAi] Cleared all motions."); return true;
case "autostack": _inventoryManager?.RunManual(cram: false, stack: true); ReplyOk("[RynthAi] AutoStack: stacking your inventory."); return true;
case "autocram": _inventoryManager?.RunManual(cram: true, stack: false); ReplyOk("[RynthAi] AutoCram: moving items into side packs."); return true;
// /ub opt list|get|set stay on the /mt opt handler (it knows the Mag-Tools
// option aliases); only toggle, which that one lacks, is handled here.
case "opt" when args.StartsWith("toggle", StringComparison.OrdinalIgnoreCase):
UbOpt(args); return true;
case "help": UbHelp(); return true;
case "simplejump": UbSimpleJump(args); return true;
case "dumpskills": UbDumpSkills(); return true;
case "quests": UbQuests(args); return true;
case "translateroute": UbTranslateRoute(args); return true;
}
return false;
}
private string EvalExpr(string expr)
{
var engine = _metaManager?.Expressions;
return engine == null ? "" : engine.Evaluate(expr);
}
// /ub delay
private void UbDelay(string args)
{
int sp = args.IndexOf(' ');
if (sp <= 0 || !int.TryParse(args.AsSpan(0, sp), out int ms) || ms < 0)
{
ReplyFail("[RynthAi] Usage: /ub delay ");
return;
}
string command = args.Substring(sp + 1).Trim();
if (command.Length == 0) { ReplyFail("[RynthAi] Usage: /ub delay "); return; }
_delayedCommands.Add((Environment.TickCount64 + ms, command, MetaCommandActive));
ReplyOk($"[RynthAi] In {ms} ms: {command}");
}
// /ub count {item | profile | player } [debug] [think]
private void UbCount(string args)
{
var words = args.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
bool think = words.RemoveAll(w => w.Equals("think", StringComparison.OrdinalIgnoreCase)) > 0;
words.RemoveAll(w => w.Equals("debug", StringComparison.OrdinalIgnoreCase));
if (words.Count < 2) { ReplyFail("[RynthAi] Usage: /ub count {item | profile | player } [think]"); return; }
string kind = words[0].ToLowerInvariant();
string what = string.Join(" ", words.Skip(1));
var inv = _objectCache?.GetDirectInventory(forceRefresh: true) ?? (IReadOnlyList)Array.Empty();
switch (kind)
{
case "item":
{
int n = 0;
foreach (var wo in inv)
if (string.Equals(wo.Name, what, StringComparison.OrdinalIgnoreCase))
n += Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
UbSay($"You have {n} {what}.", think);
break;
}
case "profile":
{
string path = ResolveLootProfilePath(what);
if (path.Length == 0 || !TryLoadLootProfile(path, out VTankLootProfile profile, out _)) { ReplyFail($"[RynthAi] count: loot profile not found: {what}"); return; }
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
int n = 0;
foreach (var wo in inv)
{
var rule = profile.Rules.FirstOrDefault(r => VTankLootEvaluator.Match(r, wo, ctx));
if (rule != null && rule.Action is VTankLootAction.Keep or VTankLootAction.KeepUpTo)
n += Math.Max(1, wo.Values(LongValueKey.StackCount, 1));
}
UbSay($"You have {n} items matching {Path.GetFileName(path)}.", think);
break;
}
case "player":
{
if (!double.TryParse(what, NumberStyles.Float, CultureInfo.InvariantCulture, out double range)) { ReplyFail("[RynthAi] Usage: /ub count player "); return; }
int n = 0;
int me = unchecked((int)_playerId);
if (_objectCache != null)
foreach (var wo in _objectCache.GetLandscapeObjects())
if (wo.Id != me && wo.ObjectClass == AcObjectClass.Player && _objectCache.Distance(me, wo.Id) <= range) n++;
UbSay($"There are {n} players within {range} meters.", think);
break;
}
default:
ReplyFail("[RynthAi] Usage: /ub count {item | profile | player } [think]");
break;
}
}
private static string ResolveLootProfilePath(string name)
{
string n = name.Trim().Trim('"');
if (File.Exists(n)) return n;
string folder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "LootProfiles");
foreach (string cand in new[] { n, n + ".utl", n + ".json" })
{
string p = Path.Combine(folder, cand);
if (File.Exists(p)) return p;
}
return "";
}
// /ub date[utc] [format]
private void UbDate(string format, bool utc)
{
DateTime t = utc ? DateTime.UtcNow : RynthClock.Now;
string s;
try { s = format.Length > 0 ? t.ToString(format, CultureInfo.InvariantCulture) : t.ToString(CultureInfo.InvariantCulture); }
catch (FormatException) { ReplyFail($"[RynthAi] Bad date format: {format}"); return; }
ChatLine("[RynthAi] " + s);
}
private void UbId()
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { ReplyFail("[RynthAi] Nothing selected."); return; }
string name = Host.TryGetObjectName(sel, out string n) ? n : "?";
ChatLine($"[RynthAi] {name}: id 0x{sel:X8} ({sel})");
}
private void UbPos()
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) sel = _playerId;
if (sel == 0 || !Host.TryGetObjectPosition(sel, out uint cell, out float x, out float y, out float z))
{
ReplyFail("[RynthAi] No position for the selected object.");
return;
}
string name = Host.TryGetObjectName(sel, out string n) ? n : "?";
string coords = NavCoordinateHelper.TryConvertPoseToCoords(cell, x, y, out double ns, out double ew)
? $"{Math.Abs(ns):F4}{(ns < 0 ? "S" : "N")}, {Math.Abs(ew):F4}{(ew < 0 ? "W" : "E")}" : "?";
ChatLine($"[RynthAi] {name}: landcell 0x{cell:X8} x={x:F3} y={y:F3} z={z:F3} ({coords})");
}
// /ub portal[p] : use the nearest portal (or NPC) by name; portalp = partial.
private void UbPortal(string name, bool partial)
{
if (name.Length == 0 || _objectCache == null || _playerId == 0) { ReplyFail("[RynthAi] Usage: /ub portal[p] "); return; }
var best = FindNearestPositioned(wo =>
(partial ? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
&& (IsPortalObject(wo) || wo.ObjectClass == AcObjectClass.Npc), out double bestD);
if (best == null) { ReplyFail($"[RynthAi] No portal named {(partial ? "like " : "")}'{name}' nearby."); LogPortalMiss("portal " + name); return; }
_navigationEngine?.Stop();
ReplyOk($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
Host.UseFor(unchecked((uint)best.Id), "Command", "/ub portal", UseKind.Asked);
}
[DllImport("winmm.dll", CharSet = CharSet.Unicode)]
private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);
// /ub playsound [volume] (volume accepted for compatibility; played at system volume)
private void UbPlaySound(string args)
{
string file = args;
int sp = args.IndexOf(' ');
if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim();
file = file.Trim('"');
if (!Path.IsPathRooted(file)) file = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, file);
if (!File.Exists(file)) { ReplyFail($"[RynthAi] Sound file not found: {file}"); return; }
try
{
if (PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/)) ReplyOk($"[RynthAi] Playing {Path.GetFileName(file)}.");
else ReplyFail($"[RynthAi] playsound: Windows couldn't play {file}.");
}
catch (Exception ex) { ReplyFail($"[RynthAi] playsound failed: {ex.Message}"); }
}
private static readonly string[] UbMotions = { "Forward", "Backward", "TurnRight", "TurnLeft", "StrafeRight", "StrafeLeft", "Walk" };
// /ub setmotion <0|1>
private void UbSetMotion(string args)
{
var w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (w.Length != 2 || (w[1] != "0" && w[1] != "1")) { ReplyFail("[RynthAi] Usage: /ub setmotion <" + string.Join("|", UbMotions) + "> <0|1>"); return; }
EvalExpr($"setmotion[`{w[0]}`,{w[1]}]");
ReplyOk($"[RynthAi] Motion {w[0]}: {(w[1] == "1" ? "on" : "off")}.");
}
private void UbGetMotion()
{
var on = UbMotions.Where(m => EvalExpr($"getmotion[`{m}`]") == "1").ToList();
ChatLine("[RynthAi] Motions on: " + (on.Count > 0 ? string.Join(", ", on) : "none"));
}
// /ub opt {list | get