using System;
using System.Linq;
using System.Text;
using UnityEngine;

namespace AvatarRefinery.ErrorGuide
{
    /// <summary>質問するときに添える環境情報（Unity の版・主要パッケージの版）。</summary>
    public static class EnvironmentInfo
    {
        static readonly string[] Interesting =
        {
            "com.vrchat.", "com.avatarrefinery.", "nadena.dev.", "jp.lilxyzw.", "com.anatawa12.", "jp.suzuryg.", "net.rs64.", "lilxyzw", "com.vrcfury."
        };

        public static string Summary()
        {
            var sb = new StringBuilder();
            sb.AppendLine("- Unity: " + Application.unityVersion);
            sb.AppendLine("- OS: " + SystemInfo.operatingSystem);
            var packages = UnityEditor.PackageManager.PackageInfo.GetAllRegisteredPackages()
                .Where(p => Interesting.Any(prefix => p.name.StartsWith(prefix)))
                .OrderBy(p => p.name)
                .Select(p => $"{p.displayName} ({p.name}) {p.version}")
                .ToList();
            sb.AppendLine(ErrorGuideText.T("- 主なパッケージ: ", "- Main packages: ") + (packages.Count == 0 ? ErrorGuideText.T("（見つかりませんでした）", "(none found)") : ""));
            foreach (var p in packages) sb.AppendLine("    - " + p);
            return sb.ToString();
        }

        public static string QuestionText(string errorMessage)
        {
            var sb = new StringBuilder();
            sb.AppendLine(ErrorGuideText.T("Unity でエラーが出て困っています。原因と直し方を教えてください。", "I am getting an error in Unity. Could you tell me the cause and how to fix it?"));
            sb.AppendLine();
            sb.AppendLine(ErrorGuideText.T("■ 環境", "■ Environment"));
            sb.Append(Summary());
            sb.AppendLine();
            sb.AppendLine(ErrorGuideText.T("■ エラー文", "■ Error message"));
            sb.AppendLine("```");
            sb.AppendLine(Trim(MaskUserPaths(errorMessage), 4000));
            sb.AppendLine("```");
            sb.AppendLine();
            sb.AppendLine(ErrorGuideText.T("■ エラーが出る直前にしたこと", "■ What I did just before the error"));
            sb.AppendLine(ErrorGuideText.T("（例: ○○の衣装を入れた / VCC で○○を更新した / アップロードしようとした）", "(e.g. imported an outfit / updated a package in VCC / tried to upload)"));
            return sb.ToString();
        }

        static string UserFolderLabel => ErrorGuideText.T("<ユーザーフォルダ>", "<user folder>");
        static string UserNameLabel => ErrorGuideText.T("<ユーザー名>", "<user name>");

        /// <summary>ユーザー名が入るフォルダのパスを伏せる（掲示板などに貼る前提のため）。</summary>
        public static string MaskUserPaths(string s)
        {
            if (string.IsNullOrEmpty(s)) return s;
            var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            if (!string.IsNullOrEmpty(home))
            {
                s = s.Replace(home, UserFolderLabel);
                s = s.Replace(home.Replace('\\', '/'), UserFolderLabel);
            }
            // 上で拾えなかった表記（C:/Users/名前、/Users/名前）もまとめて伏せる
            s = System.Text.RegularExpressions.Regex.Replace(s, @"([A-Za-z]:[\\/]Users[\\/])[^\\/\s'""]+", "$1" + UserNameLabel);
            s = System.Text.RegularExpressions.Regex.Replace(s, @"(/Users/|/home/)[^/\s'""]+", "$1" + UserNameLabel);
            return s;
        }

        static string Trim(string s, int max) => s == null ? "" : (s.Length <= max ? s : s.Substring(0, max) + ErrorGuideText.T("\n…（以下省略）", "\n… (truncated)"));
    }
}
