using System.IO;
using UnityEditor;
using UnityEngine;

namespace VibeCopilot.Editor
{
    // COMPATIBILITATE INPUT. Scripturile generate (miscare/control) folosesc Input-ul CLASIC
    // (Input.GetAxis / Input.GetKey). Unele proiecte Unity noi vin setate DOAR pe Input System-ul
    // nou (activeInputHandler = 1), caz in care Input-ul clasic ARUNCA exceptie cand dai Play.
    // Detectam asta o data si oferim sa comutam pe "Both" (2) — pastreaza si sistemul nou, dar
    // face sa mearga si codul clasic. Necesita un restart de Unity (setarea se citeste la pornire).
    [InitializeOnLoad]
    public static class VibeInputCompat
    {
        private const string AskedKey = "VibeCopilot.InputCompatAsked"; // o data pe sesiune

        static VibeInputCompat() { EditorApplication.delayCall += Ensure; }

        private static void Ensure()
        {
            if (SessionState.GetBool(AskedKey, false)) return;
            try
            {
                Object[] all = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/ProjectSettings.asset");
                if (all == null) return;
                foreach (Object o in all)
                {
                    if (o == null) continue;
                    SerializedObject so = new SerializedObject(o);
                    SerializedProperty prop = so.FindProperty("activeInputHandler");
                    if (prop == null) continue;
                    // 0 = clasic, 1 = doar Input System nou, 2 = ambele. Doar la "1" e o problema.
                    if (prop.intValue != 1) return;

                    SessionState.SetBool(AskedKey, true);
                    bool ok = EditorUtility.DisplayDialog(
                        "VibeCopilot — enable classic Input",
                        "This project is set to use ONLY Unity's new Input System, but VibeCopilot's movement " +
                        "and control scripts use classic Input (Input.GetAxis) — which throws errors when you press Play.\n\n" +
                        "Enable classic Input as well? This keeps the new Input System too. Unity will need to restart.",
                        "Enable & restart", "Not now");
                    if (!ok) return;

                    prop.intValue = 2; // Both
                    so.ApplyModifiedProperties();
                    AssetDatabase.SaveAssets();
                    EditorApplication.OpenProject(Directory.GetCurrentDirectory());
                    return;
                }
            }
            catch { /* best-effort: daca nu reusim, nu blocam nimic */ }
        }
    }
}
