using System;
using AIImages.Services;
using AIImages.Settings;
using AIImages.Validation;
using HarmonyLib;
using RimWorld;
using UnityEngine;
using Verse;

namespace AIImages
{
    /// <summary>
    /// Main mod class with settings support and dependency injection
    /// </summary>
    public class AIImagesMod : Mod
    {
        private static AIImagesMod _instance = null!;
        private readonly ServiceContainer _serviceContainer;

        /// <summary>
        /// Глобальный экземпляр мода (для доступа из других классов)
        /// </summary>
        public static AIImagesMod Instance
        {
            get
            {
                if (_instance == null)
                {
                    throw new InvalidOperationException(
                        "[AI Images] Mod instance not initialized. This should not happen."
                    );
                }
                return _instance;
            }
            private set => _instance = value;
        }

        /// <summary>
        /// Настройки мода
        /// </summary>
        public static AIImagesModSettings Settings => Instance._serviceContainer.Settings;

        /// <summary>
        /// Контейнер сервисов с dependency injection
        /// </summary>
        public static ServiceContainer Services => Instance._serviceContainer;

        public AIImagesMod(ModContentPack content)
            : base(content)
        {
            Instance = this;

            var settings = GetSettings<AIImagesModSettings>();

            // Валидируем настройки при загрузке
            var validationResult = SettingsValidator.Validate(settings);
            if (!validationResult.IsValid)
            {
                Log.Warning(
                    $"[AI Images] Settings validation failed:\n{validationResult.GetErrorsAsString()}"
                );
            }

            if (validationResult.HasWarnings)
            {
                Log.Warning(
                    $"[AI Images] Settings validation warnings:\n{validationResult.GetWarningsAsString()}"
                );
            }

            // Создаем контейнер сервисов
            try
            {
                _serviceContainer = new ServiceContainer(settings);
                Log.Message("[AI Images] Mod initialized successfully with dependency injection");
            }
            catch (Exception ex)
            {
                Log.Error(
                    $"[AI Images] Failed to initialize ServiceContainer: {ex.Message}\n{ex.StackTrace}"
                );
                throw;
            }
        }

        public override void DoSettingsWindowContents(Rect inRect)
        {
            AIImagesSettingsUI.DoSettingsWindowContents(inRect, Settings, _serviceContainer);
            base.DoSettingsWindowContents(inRect);
        }

        public override string SettingsCategory()
        {
            return "AI Images";
        }

        /// <summary>
        /// Вызывается при выгрузке мода
        /// </summary>
        public override void WriteSettings()
        {
            base.WriteSettings();

            // Валидируем настройки перед сохранением
            var validationResult = SettingsValidator.Validate(Settings);
            if (!validationResult.IsValid)
            {
                Log.Warning(
                    $"[AI Images] Saving settings with validation errors:\n{validationResult.GetErrorsAsString()}"
                );
                Messages.Message(
                    "AI Images: Some settings have validation errors. Check the log.",
                    MessageTypeDefOf.CautionInput
                );
            }
        }
    }

    /// <summary>
    /// Static constructor for Harmony patches
    /// </summary>
    [StaticConstructorOnStartup]
    public static class AIImagesHarmonyPatcher
    {
        static AIImagesHarmonyPatcher()
        {
            var harmony = new Harmony("Mrleo1nid.aiimages");
            harmony.PatchAll();
            Log.Message("[AI Images] Harmony patches applied successfully");
        }
    }
}
