using System.IO;
using AIImages.Components;
using UnityEngine;
using Verse;

namespace AIImages.Helpers
{
    /// <summary>
    /// Вспомогательный класс для работы с портретами персонажей
    /// </summary>
    public static class PawnPortraitHelper
    {
        /// <summary>
        /// Получить компонент портрета пешки
        /// </summary>
        public static PawnPortraitComp GetPortraitComp(Pawn pawn)
        {
            return pawn?.TryGetComp<PawnPortraitComp>();
        }

        /// <summary>
        /// Сохранить путь к портрету на пешке
        /// </summary>
        public static void SavePortraitPath(Pawn pawn, string path)
        {
            var comp = GetPortraitComp(pawn);
            if (comp != null)
            {
                comp.PortraitPath = path;
                Log.Message($"[AI Images] Saved portrait path for {pawn.Name}: {path}");
            }
        }

        /// <summary>
        /// Получить путь к портрету пешки
        /// </summary>
        public static string GetPortraitPath(Pawn pawn)
        {
            var comp = GetPortraitComp(pawn);
            return comp?.PortraitPath;
        }

        /// <summary>
        /// Есть ли у пешки сохраненный портрет
        /// </summary>
        public static bool HasPortrait(Pawn pawn)
        {
            var comp = GetPortraitComp(pawn);
            return comp != null && comp.HasPortrait;
        }

        /// <summary>
        /// Загрузить портрет пешки как текстуру
        /// </summary>
        public static Texture2D LoadPortrait(Pawn pawn)
        {
            string path = GetPortraitPath(pawn);

            if (string.IsNullOrEmpty(path) || !File.Exists(path))
            {
                return null;
            }

            try
            {
                byte[] imageData = File.ReadAllBytes(path);
                Texture2D texture = new Texture2D(2, 2);
                texture.LoadImage(imageData);
                return texture;
            }
            catch (System.Exception ex)
            {
                Log.Warning($"[AI Images] Failed to load portrait for {pawn.Name}: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// Очистить портрет пешки
        /// </summary>
        public static void ClearPortrait(Pawn pawn)
        {
            var comp = GetPortraitComp(pawn);
            if (comp != null)
            {
                comp.PortraitPath = null;
            }
        }

        /// <summary>
        /// Очистить все сгенерированные портреты
        /// </summary>
        public static int ClearAllPortraits(string savePath)
        {
            int deletedCount = 0;

            // Очищаем компоненты всех пешек
            if (Current.Game != null && Current.Game.Maps != null)
            {
                foreach (var map in Current.Game.Maps)
                {
                    foreach (var pawn in map.mapPawns.AllPawns)
                    {
                        var comp = GetPortraitComp(pawn);
                        if (comp != null && comp.HasPortrait)
                        {
                            comp.PortraitPath = null;
                        }
                    }
                }
            }

            // Удаляем файлы из директории
            string fullPath = Path.Combine(GenFilePaths.SaveDataFolderPath, savePath);

            if (Directory.Exists(fullPath))
            {
                try
                {
                    var files = Directory.GetFiles(fullPath, "*.png");
                    foreach (var file in files)
                    {
                        try
                        {
                            File.Delete(file);
                            deletedCount++;
                        }
                        catch (System.Exception ex)
                        {
                            Log.Warning($"[AI Images] Failed to delete file {file}: {ex.Message}");
                        }
                    }
                    Log.Message($"[AI Images] Deleted {deletedCount} portrait files");
                }
                catch (System.Exception ex)
                {
                    Log.Error($"[AI Images] Error cleaning portraits directory: {ex.Message}");
                }
            }

            return deletedCount;
        }
    }
}
