using System.Collections.Generic;

namespace HellionChat;

// Shared input history for all ChatInputBars (main and pop-out windows).
// Push deduplicates: existing entries are moved to the end when re-added.
// TEST-MIRROR: ../../Hellion Build test/Util/InputHistoryServiceTests.cs
public static class InputHistoryService
{
    private const int MaxSize = 30;
    private static readonly List<string> _entries = new();

    public static IReadOnlyList<string> Entries => _entries;

    public static int Count => _entries.Count;

    public static void Push(string entry)
    {
        if (string.IsNullOrWhiteSpace(entry))
            return;

        var trimmed = entry.Trim();

        // Move-to-newest: remove existing entry before adding at the end
        for (var i = 0; i < _entries.Count; i++)
        {
            if (_entries[i] == trimmed)
            {
                _entries.RemoveAt(i);
                break;
            }
        }

        _entries.Add(trimmed);
        if (_entries.Count > MaxSize)
            _entries.RemoveAt(0);
    }

    public static string? GetByCursor(int cursor)
    {
        if (cursor < 0 || cursor >= _entries.Count)
            return null;
        return _entries[cursor];
    }

    // Plugin reload doesn't reset static state automatically. Plugin.DisposeAsync
    // calls this so the next load starts with an empty history instead of
    // inheriting the previous session's entries.
    public static void Reset()
    {
        _entries.Clear();
    }
}
