using UnityEditor;
using UnityEditor.PackageManager;
using UnityEditor.PackageManager.Requests;
using UnityEngine;

namespace VibeCopilot.Editor
{
    // AUTO-INSTALL glTFast. Biblioteca 3D descarca fisiere .glb, dar Unity NU le poate importa
    // fara pachetul oficial "com.unity.cloud.gltfast" — fara el, modelul se descarca dar nu apare
    // in scena (LoadAssetAtPath intoarce null, vezi VibeGen3D.PlaceModel). Userii non-tehnici
    // ratau pasul manual din Package Manager. Aici verificam O DATA pe sesiune si, daca lipseste,
    // il instalam SINGURI (e pachet oficial Unity, gratis, fara cont). Best-effort: daca nu reusim,
    // nu blocam nimic — plugin-ul ramane cu mesajul de instalare manuala ca plasa de siguranta.
    [InitializeOnLoad]
    public static class VibeGltfastInstaller
    {
        private const string PkgName = "com.unity.cloud.gltfast";
        private const string DoneKey = "VibeCopilot.GltfastChecked"; // o data pe sesiune
        private static ListRequest _list;
        private static AddRequest _add;

        static VibeGltfastInstaller() { EditorApplication.delayCall += Begin; }

        private static void Begin()
        {
            if (SessionState.GetBool(DoneKey, false)) return;
            SessionState.SetBool(DoneKey, true);
            try
            {
                // offlineMode=true, includeIndirect=false -> doar pachetele instalate direct, instant.
                _list = Client.List(true, false);
                EditorApplication.update += PollList;
            }
            catch { /* best-effort */ }
        }

        private static void PollList()
        {
            if (_list == null || !_list.IsCompleted) return;
            EditorApplication.update -= PollList;
            try
            {
                if (_list.Status == StatusCode.Success)
                {
                    foreach (var p in _list.Result)
                        if (p.name == PkgName) return; // deja instalat -> nimic de facut
                }
                // Nu e instalat -> il adaugam. Declanseaza un import/recompilare Unity.
                _add = Client.Add(PkgName);
                EditorApplication.update += PollAdd;
            }
            catch { }
        }

        private static void PollAdd()
        {
            if (_add == null || !_add.IsCompleted) return;
            EditorApplication.update -= PollAdd;
            if (_add.Status == StatusCode.Success)
                Debug.Log("[VibeCopilot] 3D importer (glTFast) installed automatically — 3D models will now load into your scene.");
            else
                Debug.LogWarning("[VibeCopilot] Couldn't auto-install the 3D importer. Add it manually: " +
                                 "Window -> Package Manager -> + -> Add package by name -> " + PkgName);
        }
    }
}
