using System.IO;
using JetBrains.Annotations;
using LLM.Editor.Helper;
using UnityEditor;
using UnityEngine;

namespace LLM.Editor.Commands
{
    [System.Serializable]
    public class CreateScriptParams
    {
        public string scriptName;
        public string scriptContent;
    }

    [UsedImplicitly]
    public class CreateScriptCommand : ICommand
    {
        private readonly CreateScriptParams _params;

        public CreateScriptCommand(string jsonParams)
        {
            _params = jsonParams?.FromJson<CreateScriptParams>();
        }

        public CommandOutcome Execute(Data.CommandContext context)
        {
            if (_params == null || string.IsNullOrEmpty(_params.scriptName) || string.IsNullOrEmpty(_params.scriptContent))
            {
                Debug.LogError("[CreateScriptCommand] Invalid parameters.");
                return CommandOutcome.Error;
            }
            
            // For simplicity, we'll save scripts to the root of the Assets folder.
            var path = Path.Combine(Application.dataPath, $"{_params.scriptName}.cs");
            File.WriteAllText(path, _params.scriptContent);
            context.CurrentSubject = path;
            Debug.Log($"[CreateScriptCommand] Created script at: {path}");
            AssetDatabase.Refresh();
            return CommandOutcome.Success;
        }
    }
}