using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Doors (2026-10-13, a mage on DreamWeave, "doors aren't opening"): the use went out while the
// client was busy (portal space), a second use followed 3 s later with the first unanswered (the
// server's walk to the door took up to 3.7 s), and a door still closed after a use was called
// locked and sent to the lockpick cooldown although the server never said so. See the header of
// DoorInteractionController.cs for the rules these check.
internal static class DoorTests
{
private const uint Player = 0x50000D01;
private const uint Door = 0x701C9139;
private const uint Pick = 0x80000D11;
private const uint Kit = 0x80000D12;
private const uint Closed = 0x00010018, Ethereal = 0x4;
private const uint BfDoor = 0x1000;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
private static (uint Cell, float X, float Y, float Z) Me0 => (0x01C90231u, 60f, 10f, 0f);
public static void Register(Runner r)
{
r.Add("door: no use while the client is busy or another use is unanswered; it goes when they clear", WaitsForBusyAndAnswer);
r.Add("door: a slow server walk (3.7 s to the answer) is waited out - one use, no retry, opened", SlowWalkOneUse);
r.Add("door: no second use while the first is unanswered; a lost use is re-sent only after the answer limit", NoDoubleUse);
r.Add("door: still closed after an answered use, no 'locked' from the server: used again, never picked", NotLockedWithoutServer);
r.Add("door: the server says locked: a lockpick goes on it, then the door is opened again", LockedUsesLockpick);
r.Add("door: locked and no lockpick: cooldown, and the door is skipped a while", LockedNoPick);
r.Add("door: nothing in portal space, nor just after it", NothingInPortalSpace);
r.Add("door: a door that opens is released at once (no fixed waits)", OpensFast);
r.Add("door: 'locked' from chat counts only as the server's line, not a player's", LockedChatLine);
r.Add("door: Only Doors On My Path - a door beside the way is left shut, one straight ahead is opened", PathOnlyAhead);
r.Add("door: Only Doors On My Path - on a route the door on the next leg goes, not a nearer one beside it", PathOnlyRoute);
r.Add("door: Only Doors On My Path - not a door past the range along the path, nor one behind the route's direction", PathOnlyRange);
r.Add("door: one created before its position was readable (just after a portal) is still found and opened", CreatedBeforePosition);
}
///
/// A dungeon's objects arrive while the character is still in portal space, often before their
/// position reads: such a door was filed as inventory and never seen by the door scans (Dargoth
/// Hera, Infested Mine, 2026-10-19: Open Doors on, a closed door on the route, no use at all).
///
private static void CreatedBeforePosition() => With(() =>
{
foreach (uint? itemType in new uint?[] { 0x80u, null }) // a readable item type, and none at all
{
var b = new Bot();
MoveDoor(Door, 40f, 0f); // the rig's door far out of range
FakeHost.Names[Door2] = "Door";
FakeHost.Bitfields[Door2] = BfDoor;
FakeHost.ObjectStates[Door2] = Closed;
if (itemType is uint t) FakeHost.ItemTypes[Door2] = t;
b.Cache.OnCreateObject(Door2); // no position yet
for (int i = 0; i < 12; i++) b.Cache.Tick(); // classified (and any retries spent) without one
Check.True(b.Cache.GetLandscapeObjects().Any(o => unchecked((uint)o.Id) == Door2),
$"a static door stays a world object without a position (item type {(itemType is null ? "unreadable" : "0x80")})");
Check.False(b.Cache.GetInventory().Any(o => unchecked((uint)o.Id) == Door2), "never filed as inventory");
FakeHost.Positions[Door2] = (Me0.Cell, Me0.X + 2f, Me0.Y, Me0.Z); // the position comes in
b.Tick();
b.Run(300);
Check.Eq(Uses(Door2), 1, "the door is used once it has a position");
}
});
// ── Rig ─────────────────────────────────────────────────────────────────
private sealed class Bot
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new() { IsMacroRunning = true, OpenDoors = true, OpenDoorRange = 5f, AutoUnlockDoors = true };
public readonly WorldObjectCache Cache;
public long Now = 50_000_000;
public readonly RynthCoreHost Host;
public Bot(bool lockpick = true)
{
FakeHost.Reset();
FakeHost.WeaponCalls = true; // UseObject
FakeHost.UseOnCalls = true; // UseObjectOn (the lockpick)
FakeHost.ServerGates = true; // GetUseDoneSeq, GetCastBusyState
FakeHost.LastUseDoneCalls = true;
FakeHost.StopCalls = true;
FakeHost.Names[Player] = "Mage";
FakeHost.Positions[Player] = Me0;
FakeHost.PlayerPose = Me0;
FakeHost.Names[Door] = "Door";
FakeHost.Positions[Door] = (Me0.Cell, Me0.X + 2f, Me0.Y, Me0.Z);
FakeHost.Bitfields[Door] = BfDoor;
FakeHost.ObjectStates[Door] = Closed;
FakeHost.Names[Pick] = "Plain Lockpick";
FakeHost.Names[Kit] = "Treated Healing Kit";
Host = FakeHost.Create(Player);
ActionPacer.Reset();
ActionPacer.Enabled = true;
ActionPacer.NowMs = () => Now;
UseAudit.Reset("RynthAi", () => true);
UseAudit.NowMs = () => Now;
UseAudit.TrackWorldUses = true;
MoveAudit.Reset();
MoveAudit.NowMs = () => Now;
var rec = typeof(RynthAiPlugin).GetMethod("RecordUseForPacing", Any)!;
UseAudit.AfterSend = (h, u) => rec.Invoke(null, new object[] { h, u });
RynthAiPlugin.DoorClock = () => Now;
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_profileLoaded", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!.SetValue(dash, true); // a stand-in with its profile in memory
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
Cache = new WorldObjectCache(Host);
Cache.SetPlayerId(Player);
Set("_objectCache", Cache);
Set("_playerId", Player);
Cache.OnCreateObject(Player);
Cache.OnCreateObject(Door);
_ = Cache[unchecked((int)Pick)];
_ = Cache[unchecked((int)Kit)];
Cache.Tick();
if (lockpick)
S.ConsumableRules.Add(new ConsumableRule { Id = unchecked((int)Pick), Name = "Plain Lockpick", Type = "Lockpick" });
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public T Get(string f) => (T)typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P)!;
public int Busy { set => Set("_busyCount", value); }
public string State => Get