using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace VCam.Exporter.Util
{
    /// <summary>
    /// Small streaming JSON writer. Unity's JsonUtility cannot write dictionaries or
    /// arbitrary object graphs, and we do not want a Newtonsoft dependency in avatar projects.
    /// Usage: BeginObject / Name / Value / EndObject. Commas are handled automatically.
    /// </summary>
    internal sealed class JsonWriter
    {
        private readonly StringBuilder _sb = new StringBuilder();
        // true = the current container already has at least one element (so the next one needs a comma)
        private readonly Stack<bool> _hasItems = new Stack<bool>();
        private bool _afterName;

        public override string ToString() => _sb.ToString();

        private void BeforeValue()
        {
            if (_afterName)
            {
                _afterName = false;
                return;
            }
            if (_hasItems.Count > 0)
            {
                if (_hasItems.Peek()) _sb.Append(',');
                _hasItems.Pop();
                _hasItems.Push(true);
            }
        }

        public JsonWriter BeginObject()
        {
            BeforeValue();
            _sb.Append('{');
            _hasItems.Push(false);
            return this;
        }

        public JsonWriter EndObject()
        {
            _hasItems.Pop();
            _sb.Append('}');
            return this;
        }

        public JsonWriter BeginArray()
        {
            BeforeValue();
            _sb.Append('[');
            _hasItems.Push(false);
            return this;
        }

        public JsonWriter EndArray()
        {
            _hasItems.Pop();
            _sb.Append(']');
            return this;
        }

        public JsonWriter Name(string name)
        {
            BeforeValue();
            WriteString(name);
            _sb.Append(':');
            _afterName = true;
            return this;
        }

        public JsonWriter Null()
        {
            BeforeValue();
            _sb.Append("null");
            return this;
        }

        public JsonWriter Value(string s)
        {
            if (s == null) return Null();
            BeforeValue();
            WriteString(s);
            return this;
        }

        public JsonWriter Value(bool b)
        {
            BeforeValue();
            _sb.Append(b ? "true" : "false");
            return this;
        }

        public JsonWriter Value(long n)
        {
            BeforeValue();
            _sb.Append(n.ToString(CultureInfo.InvariantCulture));
            return this;
        }

        public JsonWriter Value(double d)
        {
            BeforeValue();
            // JSON has no NaN/Infinity; write null so the file stays valid.
            if (double.IsNaN(d) || double.IsInfinity(d)) _sb.Append("null");
            else _sb.Append(d.ToString("R", CultureInfo.InvariantCulture));
            return this;
        }

        /// <summary>
        /// float overload: "R" on the float itself gives the shortest round-trip text ("0.348"),
        /// instead of widening to double first ("0.34799998998641968"). Keeps glTF JSON small.
        /// </summary>
        public JsonWriter Value(float f)
        {
            BeforeValue();
            if (float.IsNaN(f) || float.IsInfinity(f)) _sb.Append("null");
            else _sb.Append(f.ToString("R", CultureInfo.InvariantCulture));
            return this;
        }

        public JsonWriter Prop(string name, string v) => Name(name).Value(v);
        public JsonWriter Prop(string name, bool v) => Name(name).Value(v);
        public JsonWriter Prop(string name, long v) => Name(name).Value(v);
        public JsonWriter Prop(string name, double v) => Name(name).Value(v);

        /// <summary>
        /// Writes a plain object graph: IDictionary&lt;string, object&gt; → object, IEnumerable → array,
        /// strings/bools/numbers → values. Used for glTF JSON, which is built as dictionaries/lists.
        /// </summary>
        public JsonWriter Any(object v)
        {
            switch (v)
            {
                case null: return Null();
                case string s: return Value(s);
                case bool b: return Value(b);
                case float f: return Value(f);
                case double d: return Value(d);
                case int i: return Value(i);
                case long l: return Value(l);
                case uint ui: return Value(ui);
                case short sh: return Value(sh);
                case ushort us: return Value(us);
                case byte by: return Value(by);
                case IDictionary<string, object> dict:
                    BeginObject();
                    foreach (var kv in dict)
                    {
                        Name(kv.Key);
                        Any(kv.Value);
                    }
                    return EndObject();
                case System.Collections.IEnumerable seq:
                    BeginArray();
                    foreach (var item in seq) Any(item);
                    return EndArray();
                default:
                    return Value(v.ToString());
            }
        }

        public JsonWriter Floats(params float[] values)
        {
            BeginArray();
            foreach (var v in values) Value(v);
            return EndArray();
        }

        private void WriteString(string s)
        {
            _sb.Append('"');
            foreach (var c in s)
            {
                switch (c)
                {
                    case '"': _sb.Append("\\\""); break;
                    case '\\': _sb.Append("\\\\"); break;
                    case '\n': _sb.Append("\\n"); break;
                    case '\r': _sb.Append("\\r"); break;
                    case '\t': _sb.Append("\\t"); break;
                    default:
                        if (c < 0x20) _sb.Append("\\u").Append(((int)c).ToString("x4"));
                        else _sb.Append(c);
                        break;
                }
            }
            _sb.Append('"');
        }
    }
}
