using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEngine;
using VCam.Exporter.Export;
using VCam.Exporter.Pipeline;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;

namespace VCam.Exporter
{
    internal sealed class ExportResult
    {
        public bool Ok;
        public string OutputPath;
        public string ReportPath;
        public string Summary;
    }

    /// <summary>
    /// Top-level export: bake a clone (MA/VRCFury applied) → write VRM 1.0 → save → report → delete clone.
    /// The original avatar is never modified. Menu and batch mode both call this.
    /// </summary>
    internal static class VCamExporter
    {
        public static ExportResult Export(GameObject avatar, string outputPath, ExportOptions options)
        {
            var report = new ExportReport();
            // The report file is a development check (D-092); the window and the log show the same summary.
            var result = new ExportResult { OutputPath = outputPath, ReportPath = options.writeReport ? Path.ChangeExtension(outputPath, ".vcam-report.json") : null };
            var total = Stopwatch.StartNew();

            if (AvatarBaker.IsBakedCopy(avatar))
            {
                report.Error($"'{avatar.name}'는 이미 빌드 적용된 복제본입니다. 원본 아바타를 선택하세요.");
                return Finish(result, report, total);
            }

            var bake = AvatarBaker.BakeClone(avatar);
            report.Stat("빌드 적용(ms)", total.ElapsedMilliseconds);
            if (!bake.Ok)
            {
                report.Error("빌드 적용 실패: " + bake.Error);
                return Finish(result, report, total);
            }

            try
            {
                if (options.state == ExportState.InGameDefault) StateSampler.ApplyInGameDefault(bake.Clone, report);
                report.Stat("상태 기준", options.state == ExportState.InGameDefault ? "게임 기본 상태" : "씬 그대로");

                var writer = new VrmWriter(options, report);
                var bytes = writer.Write(bake.Clone, avatar.name, outputPath);
                if (!report.HasErrors)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPath)));
                    File.WriteAllBytes(outputPath, bytes);
                    report.Stat("파일 크기(MB)", Math.Round(bytes.Length / 1048576.0, 1));
                }
            }
            catch (Exception e)
            {
                report.Error("내보내기 중 예외: " + e);
            }
            finally
            {
                if (bake.Clone != null) Object.DestroyImmediate(bake.Clone);
            }
            return Finish(result, report, total);
        }

        private static ExportResult Finish(ExportResult result, ExportReport report, Stopwatch total)
        {
            report.Stat("전체 시간(ms)", total.ElapsedMilliseconds);
            result.Ok = !report.HasErrors;
            if (result.ReportPath != null)
            {
                try
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(result.ReportPath)));
                    File.WriteAllText(result.ReportPath, report.ToJson(), new UTF8Encoding(false));
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[VCam] 보고서를 쓰지 못했습니다: " + e.Message);
                    result.ReportPath = null;
                }
            }
            var head = result.Ok ? $"내보내기 성공: {result.OutputPath}" : "내보내기 실패";
            result.Summary = head + "\n\n" + report.Summary() + (result.ReportPath != null ? "\n보고서: " + result.ReportPath : "");
            Debug.Log("[VCam] " + result.Summary);
            return result;
        }
    }
}
