using System.Collections.Generic;
using System.Linq;
using System.Text;
using VCam.Exporter.Util;

namespace VCam.Exporter.Export
{
    /// <summary>
    /// Collects what happened during an export: errors (export unusable), warnings (something will look or
    /// behave differently from Unity) and stats. Written next to the .vrm as &lt;name&gt;.vcam-report.json.
    /// The "export exactly what Unity shows" requirement means every known difference must surface here.
    /// </summary>
    internal sealed class ExportReport
    {
        public readonly List<string> Errors = new List<string>();
        public readonly List<string> Warnings = new List<string>();
        public readonly List<string> Notes = new List<string>();
        public readonly SortedDictionary<string, object> Stats = new SortedDictionary<string, object>();

        public void Error(string message) => Errors.Add(message);
        public void Warn(string message) => Warnings.Add(message);
        public void Note(string message) => Notes.Add(message);
        public void Stat(string key, object value) => Stats[key] = value;

        public bool HasErrors => Errors.Count > 0;

        public string ToJson()
        {
            var w = new JsonWriter();
            w.BeginObject();
            w.Name("errors").Any(Errors);
            w.Name("warnings").Any(Warnings);
            w.Name("notes").Any(Notes);
            w.Name("stats").Any(Stats.ToDictionary(kv => kv.Key, kv => kv.Value));
            w.EndObject();
            return w.ToString();
        }

        public string Summary(int maxLines = 12)
        {
            var sb = new StringBuilder();
            foreach (var kv in Stats) sb.AppendLine($"{kv.Key}: {kv.Value}");
            void List(string title, List<string> items)
            {
                if (items.Count == 0) return;
                sb.AppendLine();
                sb.AppendLine($"{title} {items.Count}개:");
                foreach (var s in items.Take(maxLines)) sb.AppendLine(" - " + s);
                if (items.Count > maxLines) sb.AppendLine($" - … 외 {items.Count - maxLines}개 (보고서 파일 참고)");
            }
            List("오류", Errors);
            List("경고", Warnings);
            return sb.ToString();
        }
    }
}
