using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using AxCopilot.Models;

namespace AxCopilot.Services.Agent;

public class McpTool : IAgentTool
{
	private readonly McpClientService _client;

	private readonly McpToolDefinition _def;

	public string Name => "mcp_" + _def.ServerName + "_" + _def.Name;

	public string Description => "[MCP:" + _def.ServerName + "] " + _def.Description;

	public ToolParameterSchema Parameters
	{
		get
		{
			ToolParameterSchema toolParameterSchema = new ToolParameterSchema
			{
				Properties = new Dictionary<string, ToolProperty>(),
				Required = new List<string>()
			};
			foreach (var (text2, mcpParameterDef2) in _def.Parameters)
			{
				toolParameterSchema.Properties[text2] = new ToolProperty
				{
					Type = mcpParameterDef2.Type,
					Description = mcpParameterDef2.Description
				};
				if (mcpParameterDef2.Required)
				{
					toolParameterSchema.Required.Add(text2);
				}
			}
			return toolParameterSchema;
		}
	}

	public McpTool(McpClientService client, McpToolDefinition def)
	{
		_client = client;
		_def = def;
	}

	public async Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct = default(CancellationToken))
	{
		try
		{
			if (!_client.IsConnected)
			{
				return ToolResult.Fail("MCP 서버 '" + _def.ServerName + "'에 연결되어 있지 않습니다.");
			}
			Dictionary<string, object> arguments = new Dictionary<string, object>();
			if (args.ValueKind == JsonValueKind.Object)
			{
				foreach (JsonProperty prop in args.EnumerateObject())
				{
					Dictionary<string, object> dictionary = arguments;
					string name = prop.Name;
					JsonValueKind valueKind = prop.Value.ValueKind;
					if (1 == 0)
					{
					}
					object value = valueKind switch
					{
						JsonValueKind.String => prop.Value.GetString(), 
						JsonValueKind.Number => prop.Value.GetDouble(), 
						JsonValueKind.True => true, 
						JsonValueKind.False => false, 
						_ => prop.Value.ToString(), 
					};
					if (1 == 0)
					{
					}
					dictionary[name] = value;
				}
			}
			return ToolResult.Ok(await _client.CallToolAsync(_def.Name, arguments, ct));
		}
		catch (Exception ex)
		{
			Exception ex2 = ex;
			return ToolResult.Fail("MCP 도구 실행 실패: " + ex2.Message);
		}
	}
}
