#if UNITY_EDITOR

// MSDK 3.0.0 .unitypackage 산출 — 배포 모듈명과 1:1 인 8개 플러그인.
//
// 기존 PerformBuild.cs 는 건드리지 않는다. 같은 파일을 고치면 그 코드를 부르는
// 기존 Jenkins 잡의 산출물이 즉시 바뀌므로, 별도 클래스로 두어 병행 운영과
// 롤백이 가능하게 한다. 에디터 메뉴도 "Stove/CI-3.0/" 으로 분리했다.
//
// 네임스페이스를 두지 않은 것은 의도적이다 — 기존 CI 진입점 PerformBuild 와 같은
// 전역 스코프여야 -executeMethod 인자가 짧고, 잡 설정에서 오타가 날 여지가 줄어든다.
//
// 배치 실행:
//   Unity -batchmode -quit -nographics -projectPath <proj> \
//         -executeMethod StoveExport30.All \
//         -packageVersion 3.0.0 -outputDir <dir> -logFile -
//
// 검증만:
//   ... -executeMethod StoveExport30.VerifyOnly
//
// 경계의 원본은 unity-deploy-unit-design.md 와 그 부속 tobe_pkg.json 이다.
// 아래 Specs 를 고치면 그쪽도 함께 갱신할 것.

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

public static class StoveExport30
{
    const string Menu = "Stove/CI-3.0/";
    const string Root = "Assets/Stove";

    const string DefaultVersion = "3.0.0";

    // .meta 는 목록에 넣지 않는다 — ExportPackage 가 자산마다 자동으로 함께 담는다.
    static readonly string[] IgnoreExtensions = { ".meta" };
    static readonly string[] IgnoreFileNames = { ".DS_Store" };

    /// <summary>플러그인 하나의 파일 경계.</summary>
    sealed class Spec
    {
        public string Name;

        /// <summary>재귀로 훑을 폴더 (Root 기준 상대 경로). 플러그인당 하나.</summary>
        public string[] Directories = new string[0];

        /// <summary>폴더 밖에서 개별로 담을 파일 (Root 기준 상대 경로).
        ///
        /// iOS 브리지는 공용 계층을 따옴표로 참조해 한 디렉터리에 있어야 하므로
        /// Plugins/iOS/ 하나를 공유한다. 그래서 폴더가 아니라 파일로 지목한다.
        /// .unitypackage 는 패키지 경계와 폴더 경계가 무관하므로 여러 패키지가
        /// 같은 디렉터리에 파일을 부어도 되고, 설치하면 한 폴더에 모인다.
        /// 2.9.x 가 같은 방식이었고 Firebase 도 12개 패키지가 한 폴더를 공유한다.</summary>
        public string[] Files = new string[0];

        // ── 배포 계약 ────────────────────────────────────────────────────
        // 아래 네 항목은 지금은 문서·검증용이지만, UPM 전환 시 package.json 의
        // name / dependencies 와 가이드의 좌표표로 그대로 옮겨 간다. 산출물과
        // 계약을 한자리에 두어 갈라지지 않게 한다.

        /// <summary>UPM 패키지 id (reverse-DNS). UPM 전환 시 package.json 의 name.</summary>
        public string PackageName;

        /// <summary>먼저 임포트돼야 하는 플러그인. UPM 전환 시 package.json 의 dependencies.</summary>
        public string[] Dependencies = new string[0];

        /// <summary>이 플러그인을 넣으면 게임이 추가해야 하는 Gradle 좌표.
        /// 의존은 모두 api 로 전이되므로 상위 좌표는 적지 않는다.</summary>
        public string[] GradleCoordinates = new string[0];

        /// <summary>위 좌표에 더해 반드시 하나만 골라야 하는 좌표.</summary>
        public string[] GradleCoordinateAlternatives = new string[0];

        /// <summary>이 플러그인이 요구하는 iOS pod.</summary>
        public string[] Pods = new string[0];

        /// <summary>같은 값을 가진 플러그인끼리는 동시에 임포트할 수 없다(빌드당 택1).</summary>
        public string ExclusiveGroup;
    }

    // ── 8개 플러그인 경계 ────────────────────────────────────────────────────
    //
    // 경계 원칙: SDK/ 아래 폴더 하나 = 플러그인 하나 = 배포 좌표 하나.
    // 각 Spec 은 폴더 하나만 가리킨다. 제외 목록도 개별 파일 목록도 없다 —
    // 자산이 잘못된 플러그인에 섞여 드는 사고가 설정이 아니라 구조상 불가능하다.
    //
    // 배치는 두 축으로 갈라 정한다 — .unitypackage 는 패키지 경계와 폴더 경계가
    // 무관하므로, 폴더는 네이티브 의존성이 정하고 배정은 배포 선택이 정한다.
    //
    //   Plugins/iOS/                    .h .m .mm — 공유 디렉터리 (배정은 Spec.Files)
    //   SDK/<패키지>/Plugins/Android/   .kt       — 패키지별
    //   SDK/<패키지>/<기능>/Interface/  C# 바인딩만
    //
    // iOS 브리지가 한 디렉터리인 이유는 기능 브리지의 헤더가 공용 계층
    // (StoveSDKNativeInterface.h 등 6개)을 따옴표로 참조하기 때문이다. 따옴표
    // include 는 자기 디렉터리를 먼저 찾고, Unity 는 Assets 트리를 Libraries/ 로
    // 그대로 복제한다(Assets/ 접두사만 제거 — 생성된 Xcode 프로젝트로 확인). 디렉터리를
    // 패키지별로 나누면 상대경로를 소스에 박아야 하는데, 조사한 어떤 SDK 도 그렇게
    // 하지 않는다 — 전부 iOS 소스를 한 폴더에 모으기 때문이다(Firebase 는 12개 패키지가
    // Assets/Plugins/iOS/Firebase/ 하나를 공유한다).
    //
    // .kt 는 package 선언으로 묶여 경로 의존이 없으므로 패키지별 폴더에 둔다.
    // 두 플랫폼의 배치가 다른 것은 코드의 실제 차이를 반영한 것이다.
    //
    // (1) 왜 기능 패키지에 배정하나 — 2.9.x 가 그랬다(Iap 패키지가
    //     IAPNativeInterface 를 함께 담았다). 그래서 CP사의 규칙이 "패키지를 받으면
    //     그 좌표·pod 을 넣고 안 받으면 아무것도 넣지 않는다" 한 줄로 유지된다.
    //     브리지를 필수 패키지에 몰아넣으면 pod 을 빠뜨렸을 때 빌드가 성공하고
    //     런타임에 조용히 죽는다 — 실수가 드러나는 시점이 빌드에서 런타임으로 밀린다.
    //
    // (2) 왜 Plugins/<플랫폼> 이라는 이름인가 — Unity 는 확장자로 플러그인 여부를 판단하고
    //     포함 여부는 .meta 가 정하므로 이 경로는 필수가 아니다(공식 문서: 경로는
    //     임포트 기본값을 고르는 데만 쓰인다). 그럼에도 이 이름을 쓰는 이유는
    //     (a) Unity 가 이 경로에 플랫폼 기본값을 자동 부여해 .meta 유실이나 신규
    //     파일 추가 시 2차 방어선이 되고 — 이 리포는 .gitignore 때문에 .meta 23개가
    //     빠진 전례가 있다 — (b) Firebase·AppsFlyer·AppLovin·GooglePlayGames·
    //     GoogleMobileAds·HIVE 가 모두 같은 이름을 써 CP사 엔지니어가 즉시 알아본다.
    //     조사한 7개 SDK 계열 중 6개가 Plugins/<플랫폼> 이었고 예외는 Adjust
    //     (Native/<플랫폼>) 하나였다.
    //
    // (3) 왜 Interface/ 에서 .kt 를 뺐나 — 그 폴더가 C# 바인딩과 네이티브를 함께
    //     담아 같은 이름이 두 가지를 가리켰다. 네이티브를 Interface 라는 이름의
    //     폴더에 담는 SDK 는 조사 대상 중 한 곳도 없었다.
    //
    // 근거와 조사 결과는 docs/unity-plugin-layout.md 에 정리해 두었다.
    //
    // 예외 — Assets/Stove/Plugins/ (SDK 밖)의 두 파일은 게임 앱 진입점이고 어느
    // 기능 좌표에도 속하지 않는다. 아래 BundleOnlyAssets 참조.
    static readonly Spec[] Specs =
    {
        // 좌표 com.stove:stove / pod Stove — 필수.
        // 2.9.x 의 Base·Auth·AuthUI·Log·View 5개 모듈이 3.0.0 에서 stove 하나로
        // 통합됐으므로 SDK/Stove/ 아래 기능 폴더로 들어가 있다.
        // SDK/Stove/Plugins/iOS/ 에는 공용 계층 6개와 코어 브리지 10개만 있다.
        new Spec
        {
            Name = "Stove",
            PackageName = "com.stove.sdk",
            GradleCoordinates = new[] { "com.stove:stove" },
            Pods = new[] { "Stove" },
            Directories = new[] { "SDK/Stove" },

            // 공용 계층 6 + 코어 브리지 10. 나머지 브리지는 각 기능 Spec 이 지목한다.
            Files = new[]
            {
                "Plugins/iOS/StoveSDKNativeInterface.h",   "Plugins/iOS/StoveSDKNativeInterface.mm",
                "Plugins/iOS/StoveSDKNativeCallbackPayload.h", "Plugins/iOS/StoveSDKNativeCallbackPayload.m",
                "Plugins/iOS/StoveSDKNativeNotifyPayload.h",   "Plugins/iOS/StoveSDKNativeNotifyPayload.m",
                "Plugins/iOS/BaseNativeInterface.h",       "Plugins/iOS/BaseNativeInterface.mm",
                "Plugins/iOS/AuthNativeInterface.h",       "Plugins/iOS/AuthNativeInterface.mm",
                "Plugins/iOS/AuthUINativeInterface.h",     "Plugins/iOS/AuthUINativeInterface.mm",
                "Plugins/iOS/LogNativeInterface.h",        "Plugins/iOS/LogNativeInterface.mm",
                "Plugins/iOS/ViewNativeInterface.h",       "Plugins/iOS/ViewNativeInterface.mm",
            },
        },

        // 좌표 stove-providers / pod StoveProviders — 프로바이더 7종.
        // GPG 만 .kt 래퍼를 갖지만 요구 좌표는 같다. play-services-games-v2 는
        // 게임이 PGS 로그인을 직접 수행하기 때문에 필요한 것이고, SDK 배포 자산은
        // com.google.android.gms 를 참조하지 않는다.
        new Spec
        {
            Name = "StoveProviders",
            PackageName = "com.stove.sdk.providers",
            Dependencies = new[] { "Stove" },
            GradleCoordinates = new[] { "com.stove:stove-providers" },
            Pods = new[] { "StoveProviders" },
            Directories = new[] { "SDK/StoveProviders" },
        },

        // 좌표 stove-iap / pod StoveIAP2 — 마켓 중립 코어.
        new Spec
        {
            Name = "StoveIAP",
            PackageName = "com.stove.sdk.iap",
            Dependencies = new[] { "Stove" },
            GradleCoordinates = new[] { "com.stove:stove-iap" },
            Pods = new[] { "StoveIAP2" },
            Directories = new[] { "SDK/StoveIAP" },
            Files = new[] { "Plugins/iOS/IAPNativeInterface.h", "Plugins/iOS/IAPNativeInterface.mm" },
        },

        // 마켓별 — Android 전용(C# 이 모두 #if UNITY_ANDROID 이고 iOS 인터페이스가
        // 없다. iOS 는 App Store 단일로 StoveIAP2 가 흡수한다). 빌드당 하나만.
        //
        // 2.9.x 는 이 셋이 SDK/IAP 아래에 있어서 코어를 재귀로 훑으면 함께 담겼고,
        // 실제로 ONEStore 가 Iap 패키지에 누출돼 안 쓰는 게임도 stove-iap-onestore
        // 좌표를 넣어야 했다. 3.0.0 은 형제 폴더로 분리해 그 사고를 구조적으로
        // 불가능하게 만들었다 — 제외 목록 같은 설정에 의존하지 않는다.
        new Spec
        {
            Name = "StoveIAPGoogle",
            PackageName = "com.stove.sdk.iap.google",
            Dependencies = new[] { "StoveIAP" },
            GradleCoordinates = new[] { "com.stove:stove-iap-google" },
            ExclusiveGroup = "android-iap-market",
            Directories = new[] { "SDK/StoveIAPGoogle" },
        },
        new Spec
        {
            Name = "StoveIAPHuawei",
            PackageName = "com.stove.sdk.iap.huawei",
            Dependencies = new[] { "StoveIAP" },
            GradleCoordinates = new[] { "com.stove:stove-iap-huawei" },
            ExclusiveGroup = "android-iap-market",
            Directories = new[] { "SDK/StoveIAPHuawei" },
        },
        new Spec
        {
            Name = "StoveIAPONEStore",
            PackageName = "com.stove.sdk.iap.onestore",
            Dependencies = new[] { "StoveIAP" },
            GradleCoordinates = new[] { "com.stove:stove-iap-onestore" },
            ExclusiveGroup = "android-iap-market",
            Directories = new[] { "SDK/StoveIAPONEStore" },
        },

        // 좌표 stove-push (+ stove-push-firebase | -huawei 택1) / pod StovePush — 필수.
        // 백엔드별 자산은 없다 — PushInitializer 가 ContentProvider 로 자동 등록되므로
        // Gradle 좌표만 고르면 된다.
        new Spec
        {
            Name = "StovePush",
            PackageName = "com.stove.sdk.push",
            Dependencies = new[] { "Stove" },
            GradleCoordinates = new[] { "com.stove:stove-push" },
            // 백엔드는 Unity 자산이 없다 — PushInitializer 가 ContentProvider 로
            // 자동 등록되므로 좌표만 고르면 된다. 게임 측 설정 파일
            // (google-services.json / agconnect-services.json)은 별도.
            GradleCoordinateAlternatives = new[]
            {
                "com.stove:stove-push-firebase",
                "com.stove:stove-push-huawei",
            },
            Pods = new[] { "StovePush" },
            Directories = new[] { "SDK/StovePush" },
            Files = new[] { "Plugins/iOS/PushNativeInterface.h", "Plugins/iOS/PushNativeInterface.mm" },
        },

        // 좌표 stove-gamelog / pod StoveGameLog — 3.0.0 신규.
        // 2.9.x 에서는 Log 모듈 안에 있었다(SDK/Log/GameLog.cs). pod 은 Stove 에
        // 의존하지 않지만 GameLogNativeInterface.mm 이 StoveSDKNativeInterface.h 를
        // import 하므로 플러그인은 Stove 를 필요로 한다.
        new Spec
        {
            Name = "StoveGameLog",
            PackageName = "com.stove.sdk.gamelog",
            // pod StoveGameLog 는 Stove 에 의존하지 않지만, GameLogNativeInterface.mm
            // 이 Stove 패키지의 공용 헤더를 상대경로로 쓰므로 Stove 를 필요로 한다.
            Dependencies = new[] { "Stove" },
            GradleCoordinates = new[] { "com.stove:stove-gamelog" },
            Pods = new[] { "StoveGameLog" },
            Directories = new[] { "SDK/StoveGameLog" },
            Files = new[] { "Plugins/iOS/GameLogNativeInterface.h", "Plugins/iOS/GameLogNativeInterface.mm" },
        },
    };

    // ── 진입점 ───────────────────────────────────────────────────────────────

    [MenuItem(Menu + "All")]
    public static void All()
    {
        Run(Specs.Select(s => s.Name).ToArray());
        ExportBundle();
    }

    /// <summary>전체 패키지 — 2.9.x 의 "Full SDK with Sample" 과 같은 산출물.
    ///
    /// SDK 8개 + Plugins(전체 패키지 전용 진입점) + Sample + SSTools 를 한 덩어리로 담는다.
    /// CP사에게는 참조 프로젝트로 나간다 — Sample/Editor 는 스토브 샘플 앱을 굽기
    /// 위한 자동화라 CP사가 그대로 쓰는 물건이 아니다.</summary>
    [MenuItem(Menu + "Export/Sample")]
    public static void ExportBundle()
    {
        var errors = new List<string>();
        try
        {
            errors.AddRange(Verify());
            if (errors.Count == 0)
            {
                string version = Arg("-packageVersion") ?? DefaultVersion;
                string outputDir = Arg("-outputDir");
                if (!string.IsNullOrEmpty(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }

                SortedSet<string> assets = Sweep(BundleRoots, "전체 패키지 트리", errors);
                if (errors.Count == 0)
                {
                    string fileName = "Sample-" + version + ".unitypackage";
                    string path = string.IsNullOrEmpty(outputDir)
                        ? fileName
                        : Path.Combine(outputDir, fileName);

                    AssetDatabase.ExportPackage(assets.ToArray(), path);
                    Debug.Log(string.Format("[StoveExport30] Sample(전체 패키지) — 자산 {0}개 → {1}",
                        assets.Count, path));
                }
            }
        }
        catch (Exception e)
        {
            errors.Add("예외: " + e);
        }

        Report(errors, "전체 패키지 산출");
    }

    [MenuItem(Menu + "Export/Stove")]            public static void ExportStove()            { Run("Stove"); }
    [MenuItem(Menu + "Export/StoveProviders")]   public static void ExportProviders()        { Run("StoveProviders"); }
    [MenuItem(Menu + "Export/StoveIAP")]         public static void ExportIAP()              { Run("StoveIAP"); }
    [MenuItem(Menu + "Export/StoveIAPGoogle")]   public static void ExportIAPGoogle()        { Run("StoveIAPGoogle"); }
    [MenuItem(Menu + "Export/StoveIAPHuawei")]   public static void ExportIAPHuawei()        { Run("StoveIAPHuawei"); }
    [MenuItem(Menu + "Export/StoveIAPONEStore")] public static void ExportIAPONEStore()      { Run("StoveIAPONEStore"); }
    [MenuItem(Menu + "Export/StovePush")]        public static void ExportPush()             { Run("StovePush"); }
    [MenuItem(Menu + "Export/StoveGameLog")]     public static void ExportGameLog()          { Run("StoveGameLog"); }

    /// <summary>산출 없이 검증만 한다. 잡의 Verify 스테이지용.</summary>
    [MenuItem(Menu + "Verify Only")]
    public static void VerifyOnly()
    {
        Report(Verify(), "검증");
    }

    /// <summary>배포 계약을 JSON 으로 내보낸다.
    ///
    /// 잡의 Inspect 스테이지가 구운 패키지를 이 파일과 대조하면 경계 사고를 잡을 수
    /// 있고, UPM 전환 시에는 여기 담긴 name/dependencies 가 각 package.json 으로
    /// 그대로 옮겨 간다. -outputDir 를 주면 그 아래, 없으면 프로젝트 루트에 쓴다.</summary>
    [MenuItem(Menu + "Dump Manifest")]
    public static void DumpManifest()
    {
        var errors = new List<string>();
        try
        {
            errors.AddRange(Verify());
            if (errors.Count == 0)
            {
                string version = Arg("-packageVersion") ?? DefaultVersion;
                string outputDir = Arg("-outputDir");
                if (!string.IsNullOrEmpty(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }

                string path = string.IsNullOrEmpty(outputDir)
                    ? ManifestFileName
                    : Path.Combine(outputDir, ManifestFileName);

                File.WriteAllText(path, BuildManifestJson(version));
                Debug.Log("[StoveExport30] 계약 내보냄 → " + path);
            }
        }
        catch (Exception e)
        {
            errors.Add("예외: " + e);
        }

        Report(errors, "계약 내보내기");
    }

    const string ManifestFileName = "stove-plugins.json";

    static string BuildManifestJson(string version)
    {
        var sb = new System.Text.StringBuilder();
        sb.Append("{\n  \"version\": \"").Append(version).Append("\",\n  \"plugins\": [\n");

        for (int i = 0; i < Specs.Length; i++)
        {
            Spec spec = Specs[i];
            var assets = CollectAssets(spec, new List<string>());

            sb.Append("    {\n");
            sb.Append("      \"name\": \"").Append(spec.Name).Append("\",\n");
            sb.Append("      \"packageName\": \"").Append(spec.PackageName).Append("\",\n");
            sb.Append("      \"file\": \"").Append(spec.Name).Append('-').Append(version).Append(".unitypackage\",\n");
            AppendArray(sb, "dependencies", spec.Dependencies);
            AppendArray(sb, "gradleCoordinates", spec.GradleCoordinates);
            AppendArray(sb, "gradleCoordinateAlternatives", spec.GradleCoordinateAlternatives);
            AppendArray(sb, "pods", spec.Pods);
            sb.Append("      \"exclusiveGroup\": ")
              .Append(string.IsNullOrEmpty(spec.ExclusiveGroup) ? "null" : "\"" + spec.ExclusiveGroup + "\"")
              .Append(",\n");
            AppendArray(sb, "assets", assets.ToArray(), last: true);
            sb.Append(i == Specs.Length - 1 ? "    }\n" : "    },\n");
        }

        sb.Append("  ]\n}\n");
        return sb.ToString();
    }

    static void AppendArray(System.Text.StringBuilder sb, string key, string[] values, bool last = false)
    {
        sb.Append("      \"").Append(key).Append("\": [");
        for (int i = 0; i < values.Length; i++)
        {
            sb.Append(i == 0 ? "\n        \"" : ",\n        \"").Append(values[i]).Append('"');
        }

        sb.Append(values.Length == 0 ? "]" : "\n      ]").Append(last ? "\n" : ",\n");
    }

    // ── 실행 ─────────────────────────────────────────────────────────────────

    static void Run(params string[] names)
    {
        var errors = new List<string>();
        try
        {
            errors.AddRange(Verify());
            if (errors.Count == 0)
            {
                string version = Arg("-packageVersion") ?? DefaultVersion;
                string outputDir = Arg("-outputDir");
                if (!string.IsNullOrEmpty(outputDir))
                {
                    Directory.CreateDirectory(outputDir);
                }

                foreach (string name in names)
                {
                    Spec spec = Specs.FirstOrDefault(s => s.Name == name);
                    if (spec == null)
                    {
                        errors.Add("알 수 없는 플러그인: " + name);
                        continue;
                    }

                    errors.AddRange(Export(spec, version, outputDir));
                }
            }
        }
        catch (Exception e)
        {
            errors.Add("예외: " + e);
        }

        Report(errors, "산출");
    }

    static IEnumerable<string> Export(Spec spec, string version, string outputDir)
    {
        var errors = new List<string>();
        SortedSet<string> assets = CollectAssets(spec, errors);

        if (errors.Count > 0)
        {
            return errors;
        }

        if (assets.Count == 0)
        {
            errors.Add(spec.Name + ": 담을 자산이 0개다");
            return errors;
        }

        string fileName = spec.Name + "-" + version + ".unitypackage";
        string path = string.IsNullOrEmpty(outputDir)
            ? fileName
            : Path.Combine(outputDir, fileName);

        AssetDatabase.ExportPackage(assets.ToArray(), path);

        Debug.Log(string.Format("[StoveExport30] {0} — 자산 {1}개 → {2}",
            spec.Name, assets.Count, path));
        foreach (string asset in assets)
        {
            Debug.Log("[StoveExport30]   " + asset);
        }

        return errors;
    }

    /// <summary>Spec 의 경계를 실제 자산 경로 집합으로 펼친다.</summary>
    static SortedSet<string> CollectAssets(Spec spec, List<string> errors)
    {
        var assets = new SortedSet<string>(StringComparer.Ordinal);

        foreach (string dir in spec.Directories)
        {
            string full = Root + "/" + dir;
            if (!Directory.Exists(full))
            {
                // 대소문자 불일치는 macOS·Windows 에서는 통과하고 Linux 에서만 터진다.
                // 조용히 빈 패키지가 나가지 않도록 오류로 올린다.
                errors.Add(spec.Name + ": 폴더 없음 " + full);
                continue;
            }

            Collect(full, assets);
        }

        foreach (string file in spec.Files)
        {
            string full = Root + "/" + file;
            if (File.Exists(full))
            {
                assets.Add(full.Replace('\\', '/'));
            }
            else
            {
                errors.Add(spec.Name + ": 파일 없음 " + full);
            }
        }

        return assets;
    }

    static void Collect(string dir, SortedSet<string> into)
    {
        foreach (string sub in Directory.GetDirectories(dir))
        {
            Collect(sub, into);
        }

        foreach (string file in Directory.GetFiles(dir))
        {
            if (IgnoreExtensions.Contains(Path.GetExtension(file)) ||
                IgnoreFileNames.Contains(Path.GetFileName(file)))
            {
                continue;
            }

            into.Add(file.Replace('\\', '/'));
        }
    }

    // ── 검증 게이트 ──────────────────────────────────────────────────────────
    //
    // .unitypackage 엔트리는 .meta 의 GUID 로 만들어진다. .meta 가 없으면 패키징하는
    // 기계의 Unity 가 새 GUID 를 생성해 ① 기계마다 GUID 가 다른 재현 불가능한
    // 배포물이 나오고 ② 이미 배포된 파일이 새 GUID 로 나가면 기존 게임 프로젝트에서
    // 옛 GUID 파일과 공존해 같은 클래스 중복 정의로 컴파일이 실패한다.
    // 실제로 .gitignore 의 `*.meta` 규칙(Visual Studio 섹션) 때문에 14건이 누락된
    // 적이 있다. 그래서 산출 전에 반드시 막는다.

    static readonly Regex GuidLine = new Regex(@"^guid:\s*([0-9a-f]{32})\s*$",
        RegexOptions.Multiline | RegexOptions.Compiled);

    /// <summary>플러그인 배정 검사를 받는 트리. 여기 있는 자산은 BundleOnlyAssets
    /// 를 빼고 8개 플러그인 중 정확히 하나에 담겨야 한다.</summary>
    // Plugins/ 가 포함되는 이유는 iOS 브리지가 그 아래 공유 디렉터리에 있고
    // 각 기능 Spec 이 Files 로 지목하기 때문이다. 폴더는 공유하되 배정은 기능별이다.
    static readonly string[] DistributionRoots = { "SDK", "Plugins" };

    /// <summary>.meta·GUID 검사를 받는 트리. 배정 트리보다 넓다.</summary>
    // Plugins/ 에는 배포 패키지에 속하지 않는 자산이 있다(아래 BundleOnly 참조).
    // 배정은 안 받지만 GUID 는 똑같이 안정적이어야 하므로 meta 검사는 받는다.
    static readonly string[] MetaRoots = { "SDK", "Plugins" };

    /// <summary>전체 패키지에 담는 트리. 2.9.x 의 "Full SDK with Sample" 과 같다.</summary>
    static readonly string[] BundleRoots = { "SDK", "Plugins", "Sample", "SSTools" };

    // ── 전체 패키지 전용 자산 ───────────────────────────────────────────────────────
    //
    // Assets/Stove/Plugins/ 의 두 파일은 게임 앱의 진입점이고, 어느 기능 좌표에도
    // 속하지 않는다 — AppController 는 인증 딥링크와 푸시 양쪽을, PlayerActivity 는
    // 푸시와 뷰 양쪽을 참조한다. 그래서 2.9.x 도 어느 모듈 패키지에도 넣지 못하고
    // 전체 패키지에만 실었다(2.9.0 배포본 18개 전수 확인). 3.0.0 도 같게 둔다.
    //
    // 게임이 자체 AppController·Activity 로 대체할 수 있다는 점에서도 배포 패키지의
    // 구성원이 아니다. 실수로 빠진 것과 구분하기 위해 여기 명시한다.
    static readonly string[] BundleOnlyAssets =
    {
        "Plugins/iOS/StoveSDKAppController.mm",
        "Plugins/Android/StoveUnityPlayerActivity.kt",
    };

    static List<string> Verify()
    {
        var errors = new List<string>();

        // 배포 트리 전체를 먼저 훑는다. Specs 의 폴더만 훑으면 새로 생긴 모듈 폴더가
        // 어디에도 안 담기는 사고를 잡지 못한다 — 3.0.0 의 SDK/GameLog 가 기존
        // PerformBuild.cs 에서 정확히 그렇게 빠져 있었다.
        var distribution = Sweep(DistributionRoots, "배포 트리", errors);

        // .meta 누락과 GUID 중복은 더 넓게 본다 — 전체 패키지 전용 자산도 포함.
        var guidOwners = new Dictionary<string, string>();
        foreach (string asset in Sweep(MetaRoots, "meta 검사 트리", errors))
        {
            VerifyAsset(asset, errors, guidOwners);
        }

        // Specs 가 배포 트리를 빠짐없이 덮는지.
        var assigned = new SortedSet<string>(StringComparer.Ordinal);
        foreach (Spec spec in Specs)
        {
            var specErrors = new List<string>();
            assigned.UnionWith(CollectAssets(spec, specErrors));
            errors.AddRange(specErrors);
        }

        var bundleOnly = new HashSet<string>(
            BundleOnlyAssets.Select(rel => Root + "/" + rel), StringComparer.Ordinal);

        foreach (string asset in distribution)
        {
            if (bundleOnly.Contains(asset))
            {
                if (assigned.Contains(asset))
                {
                    errors.Add("전체 패키지 전용 자산이 플러그인에도 배정됐다: " + asset);
                }

                continue;
            }

            if (!assigned.Contains(asset))
            {
                errors.Add("어느 플러그인에도 배정되지 않은 자산: " + asset);
            }
        }

        // 두 플러그인이 같은 파일을 담으면 설치 시 중복되고, 어느 좌표를 넣어야
        // 하는지도 모호해진다. Files 를 쓰는 이상 이 검사가 필요하다.
        var owner = new Dictionary<string, string>(StringComparer.Ordinal);
        foreach (Spec spec in Specs)
        {
            foreach (string asset in CollectAssets(spec, new List<string>()))
            {
                string first;
                if (owner.TryGetValue(asset, out first))
                {
                    errors.Add("두 플러그인에 중복 배정된 자산 " + asset + ": " + first + " / " + spec.Name);
                }
                else
                {
                    owner[asset] = spec.Name;
                }
            }
        }

        // 전체 패키지 전용 자산이 실제로 그 자리에 있는지. 경로가 바뀌면 전체 패키지에서 조용히
        // 빠지고, Android 는 매니페스트가 없는 클래스를 가리켜 앱이 시작되지 않는다.
        foreach (string rel in BundleOnlyAssets)
        {
            if (!File.Exists(Root + "/" + rel))
            {
                errors.Add("전체 패키지 전용 자산이 없음: " + Root + "/" + rel);
            }
        }

        errors.AddRange(VerifyContract());
        return errors;
    }

    /// <summary>루트 목록을 자산 경로 집합으로 펼친다.</summary>
    static SortedSet<string> Sweep(string[] roots, string what, List<string> errors)
    {
        var assets = new SortedSet<string>(StringComparer.Ordinal);
        foreach (string root in roots)
        {
            string full = Root + "/" + root;
            if (Directory.Exists(full))
            {
                Collect(full, assets);
            }
            else
            {
                errors.Add(what + " 폴더 없음: " + full);
            }
        }

        return assets;
    }

    /// <summary>배포 계약(§Spec 의 PackageName·Dependencies·좌표)의 자기 일관성.</summary>
    static IEnumerable<string> VerifyContract()
    {
        var errors = new List<string>();
        var names = new HashSet<string>(Specs.Select(s => s.Name));
        var packageNames = new Dictionary<string, string>();

        foreach (Spec spec in Specs)
        {
            if (string.IsNullOrEmpty(spec.PackageName))
            {
                errors.Add(spec.Name + ": PackageName 이 비어 있다 (UPM 전환 시 package.json 의 name)");
            }
            else
            {
                string owner;
                if (packageNames.TryGetValue(spec.PackageName, out owner))
                {
                    errors.Add("PackageName 중복 " + spec.PackageName + ": " + owner + " / " + spec.Name);
                }
                else
                {
                    packageNames[spec.PackageName] = spec.Name;
                }
            }

            foreach (string dep in spec.Dependencies)
            {
                if (!names.Contains(dep))
                {
                    errors.Add(spec.Name + ": 알 수 없는 의존 " + dep);
                }
                else if (dep == spec.Name)
                {
                    errors.Add(spec.Name + ": 자기 자신에 의존한다");
                }
            }

            if (spec.GradleCoordinates.Length == 0 && spec.Pods.Length == 0)
            {
                errors.Add(spec.Name + ": Gradle 좌표도 pod 도 없다 — 배포 단위와 대응하지 않는다");
            }
        }

        // 의존 순환. 플러그인이 8개뿐이라 단순 순회로 충분하다.
        foreach (Spec spec in Specs)
        {
            var seen = new HashSet<string>();
            var stack = new Stack<string>(spec.Dependencies);
            while (stack.Count > 0)
            {
                string cur = stack.Pop();
                if (cur == spec.Name)
                {
                    errors.Add(spec.Name + ": 의존 순환");
                    break;
                }

                if (!seen.Add(cur))
                {
                    continue;
                }

                Spec next = Specs.FirstOrDefault(s => s.Name == cur);
                if (next != null)
                {
                    foreach (string d in next.Dependencies)
                    {
                        stack.Push(d);
                    }
                }
            }
        }

        return errors;
    }

    static void VerifyAsset(string asset, List<string> errors, Dictionary<string, string> guidOwners)
    {
        if (!File.Exists(asset))
        {
            errors.Add("자산이 없음: " + asset);
            return;
        }

        string meta = asset + ".meta";
        if (!File.Exists(meta))
        {
            errors.Add(".meta 누락: " + asset);
            return;
        }

        Match match = GuidLine.Match(File.ReadAllText(meta));
        if (!match.Success)
        {
            errors.Add(".meta 에 guid 가 없음: " + meta);
            return;
        }

        string guid = match.Groups[1].Value;
        string owner;
        if (guidOwners.TryGetValue(guid, out owner))
        {
            errors.Add("GUID 중복 " + guid + ": " + owner + " / " + asset);
            return;
        }

        guidOwners[guid] = asset;
    }

    // ── 결과 보고 ────────────────────────────────────────────────────────────

    static void Report(IEnumerable<string> errors, string what)
    {
        List<string> list = errors.ToList();
        if (list.Count == 0)
        {
            Debug.Log("[StoveExport30] " + what + " 성공");
            return;
        }

        foreach (string error in list)
        {
            Debug.LogError("[StoveExport30] " + error);
        }

        Debug.LogError("[StoveExport30] " + what + " 실패 — 오류 " + list.Count + "건");

        // 배치 실행이면 Jenkins 가 실패로 인식하도록 종료 코드를 남긴다.
        // 에디터에서 메뉴로 실행한 경우에는 에디터를 닫아버리지 않는다.
        if (Application.isBatchMode)
        {
            EditorApplication.Exit(1);
        }
    }

    static string Arg(string name)
    {
        string[] args = Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length - 1; i++)
        {
            if (args[i] == name)
            {
                return args[i + 1];
            }
        }

        return null;
    }
}

#endif
