using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Decal.Adapter;

namespace MosswartMassacre
{
    /// <summary>
    /// Tracks rare item discoveries, handles rare meta state toggles,
    /// and sends rare notifications via WebSocket.
    /// </summary>
    internal class RareTracker
    {
        private readonly IPluginLogger _logger;
        private readonly string _characterName;

        internal int RareCount { get; set; }
        internal bool RareMetaEnabled { get; set; } = true;

        internal RareTracker(IPluginLogger logger)
        {
            _logger = logger;
            _characterName = CoreManager.Current.CharacterFilter.Name;
        }

        /// <summary>
        /// Check if the chat text is a rare discovery by this character.
        /// If so, increments count, triggers meta switch, allegiance announce, and WebSocket notification.
        /// Returns true if a rare was found.
        /// </summary>
        internal bool CheckForRare(string text, out string rareText)
        {
            if (IsRareDiscoveryMessage(text, out rareText))
            {
                RareCount++;

                if (RareMetaEnabled)
                {
                    PluginCore.Decal_DispatchOnChatCommand("/vt setmetastate loot_rare");
                }

                DelayedCommandManager.AddDelayedCommand($"/a {rareText}", 3000);
                _ = WebSocket.SendRareAsync(rareText);
                return true;
            }
            return false;
        }

        internal void ToggleRareMeta()
        {
            PluginSettings.Instance.RareMetaEnabled = !PluginSettings.Instance.RareMetaEnabled;
            RareMetaEnabled = PluginSettings.Instance.RareMetaEnabled;
        }

        private bool IsRareDiscoveryMessage(string text, out string rareTextOnly)
        {
            rareTextOnly = null;

            string pattern = @"^(?<name>['A-Za-z ]+)\shas discovered the (?<item>.*?)!$";
            Match match = Regex.Match(text, pattern);

            if (match.Success && match.Groups["name"].Value == _characterName)
            {
                rareTextOnly = match.Groups["item"].Value;
                return true;
            }

            return false;
        }
    }
}
