using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace AxCopilot.Services.Agent;

public class EnvTool : IAgentTool
{
	public string Name => "env_tool";

	public string Description => "Read or set environment variables (process scope only). Actions: 'get' — read an environment variable value; 'set' — set an environment variable (process scope, not permanent); 'list' — list all environment variables; 'expand' — expand %VAR% references in a string.";

	public ToolParameterSchema Parameters
	{
		get
		{
			ToolParameterSchema toolParameterSchema = new ToolParameterSchema();
			Dictionary<string, ToolProperty> dictionary = new Dictionary<string, ToolProperty>();
			ToolProperty obj = new ToolProperty
			{
				Type = "string",
				Description = "Action to perform"
			};
			int num = 4;
			List<string> list = new List<string>(num);
			CollectionsMarshal.SetCount(list, num);
			Span<string> span = CollectionsMarshal.AsSpan(list);
			span[0] = "get";
			span[1] = "set";
			span[2] = "list";
			span[3] = "expand";
			obj.Enum = list;
			dictionary["action"] = obj;
			dictionary["name"] = new ToolProperty
			{
				Type = "string",
				Description = "Variable name (for get/set)"
			};
			dictionary["value"] = new ToolProperty
			{
				Type = "string",
				Description = "Variable value (for set) or string to expand (for expand)"
			};
			dictionary["filter"] = new ToolProperty
			{
				Type = "string",
				Description = "Filter pattern for list action (case-insensitive substring match)"
			};
			toolParameterSchema.Properties = dictionary;
			num = 1;
			List<string> list2 = new List<string>(num);
			CollectionsMarshal.SetCount(list2, num);
			CollectionsMarshal.AsSpan(list2)[0] = "action";
			toolParameterSchema.Required = list2;
			return toolParameterSchema;
		}
	}

	public Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct = default(CancellationToken))
	{
		string text = args.GetProperty("action").GetString() ?? "";
		try
		{
			if (1 == 0)
			{
			}
			ToolResult result = text switch
			{
				"get" => Get(args), 
				"set" => Set(args), 
				"list" => ListVars(args), 
				"expand" => Expand(args), 
				_ => ToolResult.Fail("Unknown action: " + text), 
			};
			if (1 == 0)
			{
			}
			return Task.FromResult(result);
		}
		catch (Exception ex)
		{
			return Task.FromResult(ToolResult.Fail("환경변수 오류: " + ex.Message));
		}
	}

	private static ToolResult Get(JsonElement args)
	{
		if (!args.TryGetProperty("name", out var value))
		{
			return ToolResult.Fail("'name' parameter is required for get action");
		}
		string text = value.GetString() ?? "";
		string environmentVariable = Environment.GetEnvironmentVariable(text);
		return (environmentVariable != null) ? ToolResult.Ok(text + "=" + environmentVariable) : ToolResult.Ok(text + " is not set");
	}

	private static ToolResult Set(JsonElement args)
	{
		if (!args.TryGetProperty("name", out var value))
		{
			return ToolResult.Fail("'name' parameter is required for set action");
		}
		if (!args.TryGetProperty("value", out var value2))
		{
			return ToolResult.Fail("'value' parameter is required for set action");
		}
		string text = value.GetString() ?? "";
		string value3 = value2.GetString() ?? "";
		Environment.SetEnvironmentVariable(text, value3, EnvironmentVariableTarget.Process);
		return ToolResult.Ok($"✓ Set {text}={value3} (process scope)");
	}

	private static ToolResult ListVars(JsonElement args)
	{
		JsonElement value2;
		string value = (args.TryGetProperty("filter", out value2) ? (value2.GetString() ?? "") : "");
		IDictionary environmentVariables = Environment.GetEnvironmentVariables();
		List<string> list = new List<string>();
		foreach (DictionaryEntry item in environmentVariables)
		{
			string text = item.Key?.ToString() ?? "";
			string text2 = item.Value?.ToString() ?? "";
			if (string.IsNullOrEmpty(value) || text.Contains(value, StringComparison.OrdinalIgnoreCase) || text2.Contains(value, StringComparison.OrdinalIgnoreCase))
			{
				if (text2.Length > 120)
				{
					text2 = text2.Substring(0, 120) + "...";
				}
				list.Add(text + "=" + text2);
			}
		}
		list.Sort(StringComparer.OrdinalIgnoreCase);
		string text3 = $"Environment variables ({list.Count}):\n" + string.Join("\n", list);
		if (text3.Length > 8000)
		{
			text3 = text3.Substring(0, 8000) + "\n... (truncated)";
		}
		return ToolResult.Ok(text3);
	}

	private static ToolResult Expand(JsonElement args)
	{
		if (!args.TryGetProperty("value", out var value))
		{
			return ToolResult.Fail("'value' parameter is required for expand action");
		}
		string name = value.GetString() ?? "";
		string output = Environment.ExpandEnvironmentVariables(name);
		return ToolResult.Ok(output);
	}
}
