using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;

namespace VCam.Exporter.Export
{
    /// <summary>Which avatar state to export (D-025).</summary>
    internal enum ExportState
    {
        /// <summary>What the Unity scene shows (after MA/VRCFury are applied).</summary>
        Scene = 0,
        /// <summary>The state the avatar starts in inside VRChat: FX animator default states with default parameters.</summary>
        InGameDefault = 1,
    }

    /// <summary>A user-chosen blendshape for one VRM expression, overriding the automatic mapping.</summary>
    [Serializable]
    internal sealed class ExpressionOverride
    {
        /// <summary>VRM preset name ("blinkLeft") or custom expression name.</summary>
        public string expression;
        /// <summary>Renderer path relative to the avatar root (e.g. "Body").</summary>
        public string rendererPath;
        public string blendShape;
        /// <summary>true = export no blendshape for this expression even if one is found automatically.</summary>
        public bool disabled;
    }

    /// <summary>
    /// Export options. Serializable with JsonUtility so the exporter window can save them per avatar at
    /// &lt;project&gt;/UserSettings/VirtualCam/&lt;avatar&gt;.json (outside Assets, so the user's assets stay untouched, and
    /// outside the export folder, so that folder holds only .vrm files, D-092).
    /// Field names are lowerCamelCase because they are the JSON keys.
    /// </summary>
    [Serializable]
    internal sealed class ExportOptions
    {
        public int version = 1;
        public ExportState state = ExportState.Scene;
        /// <summary>Longest texture side in the output. 0 = keep original size.</summary>
        public int maxTextureSize = 2048;
        /// <summary>
        /// Write vertex TANGENT. Off by default (D-023): with tangents present, three-vrm 3.6 MToon outline
        /// hulls render as broken star shapes. Viewers compute tangents when absent (glTF allows this), and
        /// UniVRM also leaves them out by default.
        /// </summary>
        public bool exportTangents;
        /// <summary>
        /// Render reference screenshots of the real Unity look next to the .vrm (D-026). A development check: users found
        /// the extra pictures and JSON beside their .vrm confusing, so it is never saved with the avatar's settings and
        /// only batch exports (or the window's development switch) turn it on (D-092).
        /// </summary>
        [NonSerialized] public bool captureReference;
        /// <summary>Write the export report next to the .vrm as &lt;name&gt;.vcam-report.json. Development check, as above (D-092).</summary>
        [NonSerialized] public bool writeReport;
        /// <summary>Comma-separated VRM meta authors. Empty = "unknown".</summary>
        public string authors = "";
        public List<ExpressionOverride> expressionOverrides = new List<ExpressionOverride>();
        /// <summary>
        /// Folder the exporter window writes the .vrm into (D-073). Empty = &lt;project&gt;/VCamExport. Saved per avatar so
        /// the user always sees, and keeps, where the file goes.
        /// </summary>
        public string outputFolder = "";

        public string[] AuthorList()
        {
            var list = (authors ?? "").Split(',').Select(a => a.Trim()).Where(a => a.Length > 0).ToArray();
            return list.Length > 0 ? list : new[] { "unknown" };
        }

        public ExpressionOverride OverrideFor(string expression) =>
            expressionOverrides.FirstOrDefault(o => o.expression == expression);

        // ------------------------------------------------------------ persistence

        public static string SafeFileName(string name) =>
            new string(name.Select(ch => Path.GetInvalidFileNameChars().Contains(ch) ? '_' : ch).ToArray());

        public static string DefaultOutputFolder() =>
            Path.Combine(Directory.GetParent(Application.dataPath).FullName, "VCamExport");

        /// <summary>The folder the window exports to: the saved choice, or &lt;project&gt;/VCamExport.</summary>
        public string ResolvedOutputFolder() =>
            string.IsNullOrWhiteSpace(outputFolder) ? DefaultOutputFolder() : Path.GetFullPath(outputFolder);

        /// <summary>Unity keeps per-user, not-shared editor state in &lt;project&gt;/UserSettings.</summary>
        public static string SettingsPath(string avatarName) =>
            Path.Combine(Directory.GetParent(Application.dataPath).FullName, "UserSettings", "VirtualCam", SafeFileName(avatarName) + ".json");

        /// <summary>Where settings were saved before D-092: inside the export folder, next to the .vrm files.</summary>
        private static string LegacySettingsPath(string avatarName) =>
            Path.Combine(DefaultOutputFolder(), SafeFileName(avatarName) + ".vcam-settings.json");

        public static ExportOptions LoadFor(string avatarName)
        {
            var path = SettingsPath(avatarName);
            if (!File.Exists(path)) path = LegacySettingsPath(avatarName);
            if (!File.Exists(path)) return new ExportOptions();
            try
            {
                var loaded = JsonUtility.FromJson<ExportOptions>(File.ReadAllText(path, Encoding.UTF8));
                if (loaded.expressionOverrides == null) loaded.expressionOverrides = new List<ExpressionOverride>();
                return loaded;
            }
            catch (Exception e)
            {
                Debug.LogWarning($"[VCam] 설정 파일을 읽지 못해 기본값을 씁니다 ({path}): {e.Message}");
                return new ExportOptions();
            }
        }

        public void SaveFor(string avatarName)
        {
            var path = SettingsPath(avatarName);
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            File.WriteAllText(path, JsonUtility.ToJson(this, true), new UTF8Encoding(false));
            // The settings now live in UserSettings, so the old copy beside the exported .vrm files has nothing left to
            // keep; removing it leaves the export folder with only .vrm files (D-092).
            var legacy = LegacySettingsPath(avatarName);
            try
            {
                if (File.Exists(legacy)) File.Delete(legacy);
            }
            catch (Exception e)
            {
                Debug.LogWarning($"[VCam] 예전 설정 파일을 지우지 못했습니다 ({legacy}): {e.Message}");
            }
        }
    }
}
