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

namespace VibeCopilot.Editor
{
    // Construieste un rezumat-text al scenei curente (ce obiecte exista + ce e selectat),
    // ca AI-ul sa "vada" scena si sa lucreze pe obiecte REALE, nu generic.
    // Fara AI, fara cost - doar citim ce e in scena Unity.
    public static class VibeSceneContext
    {
        public static string Build()
        {
            StringBuilder sb = new StringBuilder();
            Scene scene = SceneManager.GetActiveScene();

            // Lista obiectelor (root + un nivel de copii), cu un indiciu despre tip.
            sb.Append("Objects: ");
            List<string> names = new List<string>();
            foreach (GameObject root in scene.GetRootGameObjects())
                CollectNames(root.transform, names, 0);
            sb.Append(names.Count > 0 ? string.Join(", ", names) : "(none)");

            // Obiectul selectat de user + componentele lui (ca AI-ul sa stie ce are deja).
            GameObject sel = Selection.activeGameObject;
            sb.Append("\nSelected: ");
            if (sel == null)
            {
                sb.Append("none");
            }
            else
            {
                sb.Append(sel.name).Append(" (has: ");
                List<string> comps = new List<string>();
                foreach (Component c in sel.GetComponents<Component>())
                    if (c != null) comps.Add(c.GetType().Name);
                sb.Append(comps.Count > 0 ? string.Join(", ", comps) : "Transform");
                sb.Append(")");
            }

            return sb.ToString();
        }

        // Adauga numele obiectului + tipul (primitiva), apoi copiii (max 1 nivel ca sa nu fie urias).
        private static void CollectNames(Transform t, List<string> into, int depth)
        {
            string hint = TypeHint(t.gameObject);
            into.Add(string.IsNullOrEmpty(hint) ? t.name : t.name + " (" + hint + ")");

            if (depth >= 1) return; // doar 1 nivel de copii
            for (int i = 0; i < t.childCount; i++)
                CollectNames(t.GetChild(i), into, depth + 1);
        }

        // Un indiciu scurt despre ce e obiectul (forma vizibila / camera / lumina).
        private static string TypeHint(GameObject go)
        {
            if (go.GetComponent<Camera>() != null) return "Camera";
            if (go.GetComponent<Light>() != null) return "Light";

            MeshFilter mf = go.GetComponent<MeshFilter>();
            if (mf != null && mf.sharedMesh != null) return mf.sharedMesh.name; // ex: Cube, Sphere, Capsule
            return "";
        }
    }
}
