using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace ServiceSim.Closeups.EditorTools
{
    /// <summary>
    /// 依頼270：空のストレッチャー（Closeups/Models_stretcher/stretcher.fbx。iCloud の hospital/people_3d/stretcher/ の写し）を読む・置く。
    ///   ・Rig なし・頂点を読める・材質は Models_stretcher/Materials/ に作り、FBX の色（Blender の linear の値）を sRGB に直す（228 の車いすと同じ）
    ///   ・根（Stretcher）は床の中心。足の側が +Z（進む向き）、押す手は頭の側（−Z）
    ///   ・動かす部品：Caster_FL/FR/BL/BR（車輪の向き・Y 軸まわり）、その子の CasterWheel_**（車輪の回転・X 軸まわり）。柵 Rail_L/R は上げたまま
    /// コマンド（読み込みと寸法・静止画）
    ///   Unity -batchmode -quit -projectPath … -executeMethod ServiceSim.Closeups.EditorTools.Closeup270Stretcher.Run -c270Out <出力フォルダ>
    /// </summary>
    public static class Closeup270Stretcher
    {
        public const string Dir = "Assets/ServiceSim/Closeups/Models_stretcher";
        public const string Fbx = Dir + "/stretcher.fbx";
        static readonly CultureInfo IC = CultureInfo.InvariantCulture;
        static string V(Vector3 v) { return string.Format(IC, "({0:0.0000},{1:0.0000},{2:0.0000})", v.x, v.y, v.z); }
        static string Hex(Color c) { return "#" + ColorUtility.ToHtmlStringRGB(c); }

        /// <summary>読み込みの設定（設定が違う時だけ読み直す）。材質は Models_stretcher/Materials/</summary>
        public static void Import(StringBuilder sb)
        {
            if (!AssetDatabase.IsValidFolder(Dir + "/Materials")) AssetDatabase.CreateFolder(Dir, "Materials");
            var mi = (ModelImporter)AssetImporter.GetAtPath(Fbx);
            if (mi == null) throw new Exception("FBX が無い: " + Fbx);
            bool changed = mi.animationType != ModelImporterAnimationType.None || !mi.isReadable || mi.importAnimation || mi.materialImportMode != ModelImporterMaterialImportMode.ImportStandard;
            if (changed)
            {
                mi.animationType = ModelImporterAnimationType.None;
                mi.isReadable = true;
                mi.importAnimation = false;
                mi.materialImportMode = ModelImporterMaterialImportMode.ImportStandard;
                mi.SaveAndReimport();
            }
            sb.AppendLine("stretcher.fbx：Rig " + mi.animationType + "・読み直し " + (changed ? "した" : "しない"));
            var shader = Shader.Find("Standard");
            bool remapped = false;
            foreach (var o in AssetDatabase.LoadAllAssetsAtPath(Fbx))
            {
                var fm = o as Material;
                if (fm == null) continue;
                string mp = Dir + "/Materials/" + fm.name + ".mat";
                var nm = AssetDatabase.LoadAssetAtPath<Material>(mp);
                if (nm == null) { nm = new Material(shader); AssetDatabase.CreateAsset(nm, mp); }
                nm.shader = shader;
                Color lin = fm.color;
                nm.color = lin.gamma;
                float metal = fm.HasProperty("_Metallic") ? fm.GetFloat("_Metallic") : 0f;
                nm.SetFloat("_Metallic", metal);
                nm.SetFloat("_Glossiness", metal > 0.3f ? 0.6f : 0.2f);
                EditorUtility.SetDirty(nm);
                mi.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), fm.name), nm); remapped = true;
                sb.AppendLine("  材質 " + fm.name + " " + Hex(lin) + " → " + Hex(nm.color) + "・金属 " + metal.ToString("0.00", IC));
            }
            if (remapped) mi.SaveAndReimport();
            AssetDatabase.SaveAssets();
        }

        /// <summary>設定が Import のままかを確かめるだけ（違えば止める）</summary>
        public static void CheckImport(StringBuilder sb)
        {
            var mi = (ModelImporter)AssetImporter.GetAtPath(Fbx);
            if (mi == null) throw new Exception("FBX が無い: " + Fbx);
            bool ok = mi.animationType == ModelImporterAnimationType.None && mi.isReadable && !mi.importAnimation && mi.GetExternalObjectMap().Count > 0;
            sb.AppendLine("stretcher.fbx：Rig " + mi.animationType + "・材質の割り当て " + mi.GetExternalObjectMap().Count + " 個・読み込みの設定のまま " + (ok ? "はい" : "いいえ"));
            if (!ok) throw new Exception("ストレッチャーの読み込みの設定が違う");
        }

        public static GameObject Spawn(string name) { return Closeup228Morita.Spawn(Fbx, name); }

        public static void Run()
        {
            string outDir = CloseupArgs.Get("-c270Out", "");
            if (outDir == "") throw new Exception("-c270Out がない");
            Directory.CreateDirectory(outDir);
            var sb = new StringBuilder();
            try
            {
                Import(sb);
                EditorSceneManager.OpenScene(CloseupShoot.ScenePath, OpenSceneMode.Single);
                Vector3 O = new Vector3(80f, 0f, 0f);
                var st = Spawn("Stretcher270");
                st.transform.SetPositionAndRotation(O, Quaternion.identity);
                sb.AppendLine("== 部品（根から）");
                foreach (Transform c in st.GetComponentsInChildren<Transform>(true))
                {
                    var r = c.GetComponent<Renderer>();
                    string info = r != null ? " 範囲 " + V(r.bounds.min - O) + "〜" + V(r.bounds.max - O) + " 材質 " + r.sharedMaterial.name : "";
                    sb.AppendLine("  " + c.name + " 位置 " + V(c.position - O) + " 回転 " + V(c.localEulerAngles) + " 右 " + V(c.right) + " 上 " + V(c.up) + " 前 " + V(c.forward) + info);
                }
                // 押す手：頭の側（z ＜ −0.9）の 0.9 m より上の頂点
                var all = new List<Vector3>(); var allPart = new List<string>();
                foreach (var mf in st.GetComponentsInChildren<MeshFilter>(true))
                    foreach (var v in mf.sharedMesh.vertices) { all.Add(mf.transform.TransformPoint(v) - O); allPart.Add(mf.name); }
                Vector3 mn = Vector3.one * 9, mx = -Vector3.one * 9;
                foreach (var p in all) { mn = Vector3.Min(mn, p); mx = Vector3.Max(mx, p); }
                sb.AppendLine("全体 " + V(mn) + "〜" + V(mx) + " 頂点 " + all.Count);
                foreach (var zr in new[] { new[] { -1.2f, -0.9f }, new[] { 0.9f, 1.2f } })
                {
                    var byPart = new Dictionary<string, Vector3[]>();
                    for (int i = 0; i < all.Count; i++)
                    {
                        var p = all[i]; if (p.z < zr[0] || p.z > zr[1] || p.y < 0.85f) continue;
                        if (!byPart.ContainsKey(allPart[i])) byPart[allPart[i]] = new[] { Vector3.one * 9, -Vector3.one * 9 };
                        byPart[allPart[i]][0] = Vector3.Min(byPart[allPart[i]][0], p); byPart[allPart[i]][1] = Vector3.Max(byPart[allPart[i]][1], p);
                    }
                    foreach (var kv in byPart) sb.AppendLine(string.Format("z {0}〜{1}・高さ 0.85 より上：{2} {3}〜{4}", zr[0], zr[1], kv.Key, V(kv.Value[0]), V(kv.Value[1])));
                }
                // 押す手の断面：x ごとの y・z の範囲（x を 0.05 m ごと）
                for (float x0 = -0.40f; x0 < 0.40f; x0 += 0.05f)
                {
                    Vector3 a = Vector3.one * 9, b = -Vector3.one * 9; int n = 0;
                    for (int i = 0; i < all.Count; i++) { var p = all[i]; if (p.z > -0.95f || p.y < 0.85f || p.x < x0 || p.x >= x0 + 0.05f) continue; a = Vector3.Min(a, p); b = Vector3.Max(b, p); n++; }
                    if (n > 0) sb.AppendLine(string.Format(IC, "  押す手 x {0:0.00}〜{1:0.00}：{2} 頂点 {3}〜{4}", x0, x0 + 0.05f, n, V(a), V(b)));
                }
                // 柵の上の端（x ごと）
                foreach (var rn in new[] { "Rail_L", "Rail_R" })
                {
                    var t = CloseupNurse.Find(st.transform, rn); if (t == null) continue;
                    var m = t.GetComponent<MeshFilter>().sharedMesh; Vector3 a = Vector3.one * 9, b = -Vector3.one * 9;
                    foreach (var v in m.vertices) { var p = t.TransformPoint(v) - O; if (p.y < 0.95f) continue; a = Vector3.Min(a, p); b = Vector3.Max(b, p); }
                    sb.AppendLine(rn + " 0.95 より上 " + V(a) + "〜" + V(b));
                    for (float z0 = -1.0f; z0 < 1.0f; z0 += 0.1f)
                    {
                        Vector3 c = Vector3.one * 9, d = -Vector3.one * 9; int n = 0;
                        foreach (var v in m.vertices) { var p = t.TransformPoint(v) - O; if (p.z < z0 || p.z >= z0 + 0.1f) continue; c = Vector3.Min(c, p); d = Vector3.Max(d, p); n++; }
                        if (n > 0) sb.AppendLine(string.Format(IC, "  {0} z {1:0.0}〜：{2} 頂点 {3}〜{4}", rn, z0, n, V(c), V(d)));
                    }
                }
                // 車輪
                foreach (var cn in new[] { "CasterWheel_FL", "CasterWheel_FR", "CasterWheel_BL", "CasterWheel_BR" })
                {
                    var t = CloseupNurse.Find(st.transform, cn); if (t == null) { sb.AppendLine(cn + " なし"); continue; }
                    float lo = 9f; foreach (var v in t.GetComponent<MeshFilter>().sharedMesh.vertices) lo = Mathf.Min(lo, t.TransformPoint(v).y);
                    sb.AppendLine(cn + " 中心 " + V(t.position - O) + " 下 " + lo.ToString("0.0000", IC));
                }
                // 静止画 2 枚
                var cam = UnityEngine.Object.FindObjectOfType<CloseupDirector>().cam;
                foreach (var v in new[] { new[] { "side", "2.6", "1.4", "0.4" }, new[] { "head", "-1.6", "1.6", "-2.6" } })
                {
                    cam.orthographic = false; cam.ResetAspect(); cam.fieldOfView = 40f;
                    cam.transform.position = O + new Vector3(float.Parse(v[1], IC), float.Parse(v[2], IC), float.Parse(v[3], IC));
                    cam.transform.LookAt(O + new Vector3(0f, 0.6f, 0f));
                    var rt = RenderTexture.GetTemporary(1600, 900, 24); cam.targetTexture = rt; cam.Render(); cam.targetTexture = null;
                    var prev = RenderTexture.active; RenderTexture.active = rt;
                    var tex = new Texture2D(1600, 900, TextureFormat.RGB24, false); tex.ReadPixels(new Rect(0, 0, 1600, 900), 0, 0); tex.Apply();
                    RenderTexture.active = prev; RenderTexture.ReleaseTemporary(rt);
                    File.WriteAllBytes(Path.Combine(outDir, "stretcher_" + v[0] + ".png"), tex.EncodeToPNG());
                }
            }
            catch (Exception e) { Debug.LogError(e); sb.AppendLine("エラー: " + e); }
            File.WriteAllText(Path.Combine(outDir, "stretcher270.txt"), sb.ToString(), new UTF8Encoding(false));
            Debug.Log("[C270S] done\n" + sb);
        }
    }
}
