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

namespace LLM.Editor.Commands
{
    [System.Serializable]
    public class EditScriptParams
    {
        public string scriptIdentifier;
        public string newScriptContent;
    }

    [UsedImplicitly]
    public class EditScriptCommand : ICommand
    {
        private readonly EditScriptParams _params;

        public EditScriptCommand(string jsonParams)
        {
            _params = jsonParams?.FromJson<EditScriptParams>();
        }
        
        public CommandOutcome Execute(Data.CommandContext context)
        {
            if (_params == null || string.IsNullOrEmpty(_params.scriptIdentifier) || string.IsNullOrEmpty(_params.newScriptContent))
            {
                Debug.LogError("[EditScriptCommand] Invalid parameters. Script identifier and new content are required.");
                return CommandOutcome.Error;
            }

            var path = AssetDatabase.GUIDToAssetPath(_params.scriptIdentifier);
            if (string.IsNullOrEmpty(path) || !path.EndsWith(".cs"))
            {
                Debug.LogError($"[EditScriptCommand] Could not find a valid script with GUID '{_params.scriptIdentifier}'.");
                return CommandOutcome.Error;
            }

            try
            {
                File.WriteAllText(path, _params.newScriptContent);
                Debug.Log($"[EditScriptCommand] Successfully edited script at: {path}");
                AssetDatabase.Refresh();
                return CommandOutcome.Success;
            }
            catch (System.Exception e)
            {
                Debug.LogError($"[EditScriptCommand] Failed to write to file at '{path}'. Error: {e.Message}");
                return CommandOutcome.Error;
            }
        }
    }
}