using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using LLM.Editor.Data;
using LLM.Editor.Helper;
using LLM.Editor.Commands;
using System.Collections.Generic;

namespace LLM.Editor.Core
{
    [Serializable]
    public class MemoryLogWrapper
    {
        public List<InteractionRecord> records;
    }
    
    [InitializeOnLoad]
    public static class MemoryLogger
    {
        private static List<InteractionRecord> _records = new();
        private static bool _isInitialized;
        
        private static string MemoryLogPath => Path.Combine(SessionManager.GetSessionCachePath(), "memory_log.json");

        private static void Initialize()
        {
            if (_isInitialized) return;
            LoadMemoryLog();
            _isInitialized = true;
        }

        public static void AddRecord(InteractionRecord record)
        {
            // We only want to log successful multi-step interactions, or single-step interactions that aren't part of a larger, failed plan.
            if (record.isMultiStep && record.Outcome != CommandOutcome.Success)
            {
                Debug.LogWarning($"[MemoryLogger] Skipping logging of failed multi-step interaction: {record.UserPrompt}");
                return;
            }
            
            // The embedding should already be generated and included in the record.
            if (record.PromptEmbedding == null || record.PromptEmbedding.Length == 0)
            {
                Debug.LogWarning($"[MemoryLogger] Record for prompt '{record.UserPrompt}' is missing its embedding. It will not be retrievable in the future.");
            }
            
            Initialize();
            
            _records.Add(record);
            SaveMemoryLog();
        }
        
        public static List<InteractionRecord> GetRecords()
        {
            Initialize();
            return _records;
        }

        private static void SaveMemoryLog()
        {
            if (!SessionManager.HasActiveSession()) return;
            
            var wrapper = new MemoryLogWrapper { records = _records };
            var json = wrapper.ToJson(true);
            File.WriteAllText(MemoryLogPath, json);
        }

        private static void LoadMemoryLog()
        {
            if (!SessionManager.HasActiveSession() || !File.Exists(MemoryLogPath))
            {
                _records = new List<InteractionRecord>();
                return;
            }

            var json = File.ReadAllText(MemoryLogPath);
            var wrapper = json.FromJson<MemoryLogWrapper>();
            _records = wrapper?.records ?? new List<InteractionRecord>();
            Debug.Log($"[MemoryLogger] Loaded {_records.Count} interaction records from memory log.");
        }
    }
}
