/*
Copyright © 2026 Mabel

All rights reserved. This plugin is protected by copyright law.

You may not modify, redistribute, or resell this software without explicit written permission from the copyright owner.

For any support please message me directly via Discord `mabel8686` or join my discord https://discord.gg/2GUsHZskCA

███╗   ███╗ █████╗ ██████╗ ███████╗██╗
████╗ ████║██╔══██╗██╔══██╗██╔════╝██║
██╔████╔██║███████║██████╔╝█████╗  ██║
██║╚██╔╝██║██╔══██║██╔══██╗██╔══╝  ██║
██║ ╚═╝ ██║██║  ██║██████╔╝███████╗███████╗
╚═╝     ╚═╝╚═╝  ╚═╝╚═════╝ ╚══════╝╚══════╝
*/
using Newtonsoft.Json;
using Oxide.Core;
using Rust;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("Permanent Death", "Mabel", "1.0.1")]
    [Description("Kick players after reaching the maximum number of deaths and optionally delete their entities.")]
    public class PermanentDeath : RustPlugin
    {
        #region Fields
        static Configuration config;
        StoredData storedData;
        const string DataFileName = "PermanentDeathData";
        const string BypassPermission = "permanentdeath.bypass";
        #endregion

        #region Config
        public class PermanentDeathSettings
        {
		    [JsonProperty(PropertyName = "Maximum Deaths Before Kick")] public int maxDeaths;
            [JsonProperty(PropertyName = "Count Suicides For Kick")] public bool countSuicidesForKick;
            [JsonProperty(PropertyName = "Delete Entities On Kick")] public bool deleteEntitiesOnKick;
        }
        public class Configuration
		{
			[JsonProperty(PropertyName = "Permanent Death Settings")] public PermanentDeathSettings permanentDeathSettings;
			public VersionNumber Version;

			public static Configuration DefaultConfig()
			{
				return new Configuration
				{
					permanentDeathSettings = new PermanentDeathSettings()
					{
						maxDeaths = 1,
						countSuicidesForKick = false,
                        deleteEntitiesOnKick = true
                    },
					Version = default
				};
			}
		}
		protected override void LoadConfig()
		{
			base.LoadConfig();
			try
			{
				config = Config.ReadObject<Configuration>();
				bool isNewConfig = config.Version == default;
				if (!isNewConfig && config.Version < Version)
				{
					UpdateConfig();
				}
				config.Version = Version;
				SaveConfig();
			}
			catch (Exception ex)
			{
				Debug.LogException(ex);
				PrintError($"Failed to load configuration: {ex.Message}");
			}
		}

		protected override void LoadDefaultConfig() => config = Configuration.DefaultConfig();
		protected override void SaveConfig() => Config.WriteObject(config);

		void UpdateConfig()
		{
			PrintWarning("Config update detected! Updating config values...");

			Configuration baseConfig = Configuration.DefaultConfig();
			if (config.Version < new VersionNumber(1, 0, 0))
			{
				config = baseConfig;
			}

			config.Version = Version;
			PrintWarning("Config update completed!");
		}
		#endregion

		#region Language
		protected override void LoadDefaultMessages()
		{
			lang.RegisterMessages(new Dictionary<string, string>
			{
				["KickReason"] = "You have reached the maximum number of deaths.",
                ["LoginDenied"] = "You have reached the maximum number of deaths this wipe."
            }, this);
        }
        #endregion

        #region Hooks
        void Unload() => SaveData();

        void Init()
        {
            permission.RegisterPermission(BypassPermission, this);
            LoadData();
        }

        void OnNewSave(string filename)
        {
            Puts("New save detected. Clearing permanent death data.");
            storedData.deathCounts.Clear();
            SaveData();
        }

        object OnPlayerDeath(BasePlayer player, HitInfo info)
		{
            if (player == null || player.IsNpc) return null;
            if (permission.UserHasPermission(player.UserIDString, BypassPermission)) return null;

            bool isSuicide = info != null && (info.Initiator == player || (info.damageTypes != null && info.damageTypes.GetMajorityDamageType() == DamageType.Suicide));

            if (!config.permanentDeathSettings.countSuicidesForKick && isSuicide) return null;

            ulong userId = player.userID;

            if (!storedData.deathCounts.TryGetValue(userId, out int deaths))
                deaths = 0;

            deaths++;
            storedData.deathCounts[userId] = deaths;
            SaveData();

            int maxDeaths = Math.Max(1, config.permanentDeathSettings.maxDeaths);

            if (deaths < maxDeaths) return null;

            if (config.permanentDeathSettings.deleteEntitiesOnKick)
                DeletePlayerEntities(userId);

            NextTick(() =>
            {
                if (player != null && player.IsConnected)
				{
                    player.Kick(lang.GetMessage("KickReason", this));
                }
            });

            return null;
		}

        object CanClientLogin(Network.Connection connection)
        {
            if (connection == null)
                return null;

            ulong userId = connection.userid;

            if (storedData.deathCounts.TryGetValue(userId, out int deaths) &&
                deaths >= Math.Max(1, config.permanentDeathSettings.maxDeaths))
            {
                return lang.GetMessage("LoginDenied", this);
            }

            return null;
        }
        #endregion

        #region Data
        class StoredData
        {
            [JsonProperty(PropertyName = "Player Death Counts")] public Dictionary<ulong, int> deathCounts = new();
        }

        void LoadData()
        {
            try
            {
                storedData = Interface.Oxide.DataFileSystem.ReadObject<StoredData>(DataFileName);
            }
            catch
            {
                storedData = new StoredData();
            }

            if (storedData == null || storedData.deathCounts == null)
                storedData = new StoredData();
        }

        void SaveData() => Interface.Oxide.DataFileSystem.WriteObject(DataFileName, storedData);
        #endregion

        #region Helper Methods
        void DeletePlayerEntities(ulong userId)
        {
            ConVar.Entity.DeleteBy(userId);
        }
        #endregion

        #region Commands
        [ConsoleCommand("permanentdeath.reset")]
        void ConsoleResetPlayer(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2)
            {
                arg.ReplyWith("You must be an admin to use this command.");
                return;
            }

            string steamIdText = arg.GetString(0);

            if (!ulong.TryParse(steamIdText, out ulong userId) || userId == 0)
            {
                arg.ReplyWith("Usage: permanentdeath.reset <steamid>");
                return;
            }

            if (!storedData.deathCounts.Remove(userId))
            {
                arg.ReplyWith($"No death data found for Steam ID {userId}.");
                return;
            }

            SaveData();
            arg.ReplyWith($"Cleared death data for Steam ID {userId}.");
            Puts($"Cleared death data for Steam ID {userId}.");
        }

        [ConsoleCommand("permanentdeath.resetall")]
        void ConsoleResetAll(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2)
            {
                arg.ReplyWith("You must be an admin to use this command.");
                return;
            }

            int clearedCount = storedData.deathCounts.Count;
            storedData.deathCounts.Clear();
            SaveData();

            arg.ReplyWith($"Cleared death data for {clearedCount} player(s).");
            Puts($"Cleared death data for {clearedCount} player(s).");
        }
        #endregion
    }
}