using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace IpcLibrary.Serialization {
    /// <summary>
    /// Exception异常的JSON转换器
    /// </summary>
    public class ExceptionConverter : JsonConverter<Exception> {
        public override Exception Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
            using var doc = JsonDocument.ParseValue(ref reader);
            var root = doc.RootElement;

            var message = root.TryGetProperty("message", out var msgElement) ? msgElement.GetString() : "Unknown error";
            var typeName = root.TryGetProperty("type", out var typeElement) ? typeElement.GetString() : null;

            if (!string.IsNullOrEmpty(typeName)) {
                var exceptionType = Type.GetType(typeName);
                if (exceptionType != null && typeof(Exception).IsAssignableFrom(exceptionType)) {
                    try {
                        return (Exception)Activator.CreateInstance(exceptionType, message);
                    } catch {
                        // 如果创建特定异常类型失败，返回通用异常
                    }
                }
            }

            return new Exception(message);
        }

        public override void Write(Utf8JsonWriter writer, Exception value, JsonSerializerOptions options) {
            writer.WriteStartObject();
            writer.WriteString("type", value.GetType().AssemblyQualifiedName);
            writer.WriteString("message", value.Message);
            writer.WriteString("stackTrace", value.StackTrace);
            writer.WriteEndObject();
        }
    }
}
