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

namespace AxCopilot.Services.Agent;

public class MathTool : IAgentTool
{
	public string Name => "math_eval";

	public string Description => "Evaluate a mathematical expression and return the result. Supports: +, -, *, /, %, parentheses, and common math operations. Use for calculations, unit conversions, and numeric analysis.";

	public ToolParameterSchema Parameters
	{
		get
		{
			ToolParameterSchema obj = new ToolParameterSchema
			{
				Properties = new Dictionary<string, ToolProperty>
				{
					["expression"] = new ToolProperty
					{
						Type = "string",
						Description = "Mathematical expression to evaluate (e.g. '(100 * 1.08) / 3')"
					},
					["precision"] = new ToolProperty
					{
						Type = "integer",
						Description = "Decimal places for rounding (default: 6)"
					}
				}
			};
			int num = 1;
			List<string> list = new List<string>(num);
			CollectionsMarshal.SetCount(list, num);
			CollectionsMarshal.AsSpan(list)[0] = "expression";
			obj.Required = list;
			return obj;
		}
	}

	public Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct = default(CancellationToken))
	{
		string text = args.GetProperty("expression").GetString() ?? "";
		JsonElement value;
		int digits = (args.TryGetProperty("precision", out value) ? value.GetInt32() : 6);
		if (string.IsNullOrWhiteSpace(text))
		{
			return Task.FromResult(ToolResult.Fail("수식이 비어 있습니다."));
		}
		try
		{
			string text2 = text.Replace("^", " ").Replace("Math.", "").Replace("System.", "");
			if (Regex.IsMatch(text2, "[a-zA-Z]{3,}"))
			{
				return Task.FromResult(ToolResult.Fail("함수 호출은 지원하지 않습니다. 기본 사칙연산만 가능합니다."));
			}
			DataTable dataTable = new DataTable();
			object value2 = dataTable.Compute(text2, null);
			double value3 = Convert.ToDouble(value2);
			double value4 = Math.Round(value3, digits);
			return Task.FromResult(ToolResult.Ok($"Expression: {text}\nResult: {value4}"));
		}
		catch (Exception ex)
		{
			return Task.FromResult(ToolResult.Fail("수식 평가 오류: " + ex.Message));
		}
	}
}
