using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace AxCopilot.Services.Agent;

public class WaitAgentsTool : IAgentTool
{
	public string Name => "wait_agents";

	public string Description => "Wait for sub-agents and collect their results.\nYou may wait for all sub-agents or only specific ids.\nUse completed_only=true to collect only already finished sub-agents without blocking.";

	public ToolParameterSchema Parameters => new ToolParameterSchema
	{
		Properties = new Dictionary<string, ToolProperty>
		{
			["ids"] = new ToolProperty
			{
				Type = "array",
				Description = "Optional list of sub-agent ids to collect. Omit to collect all.",
				Items = new ToolProperty
				{
					Type = "string",
					Description = "Sub-agent id"
				}
			},
			["completed_only"] = new ToolProperty
			{
				Type = "boolean",
				Description = "If true, collect only already completed sub-agents and do not wait."
			}
		},
		Required = new List<string>()
	};

	public async Task<ToolResult> ExecuteAsync(JsonElement args, AgentContext context, CancellationToken ct = default(CancellationToken))
	{
		List<string> ids = null;
		if (args.TryGetProperty("ids", out var idsEl) && idsEl.ValueKind == JsonValueKind.Array)
		{
			ids = (from x in idsEl.EnumerateArray()
				where x.ValueKind == JsonValueKind.String
				select x.GetString() ?? "" into x
				where !string.IsNullOrWhiteSpace(x)
				select x).ToList();
		}
		JsonElement completedEl;
		bool completedOnly = args.TryGetProperty("completed_only", out completedEl) && completedEl.ValueKind == JsonValueKind.True;
		return ToolResult.Ok(await SubAgentTool.WaitAsync(ids, completedOnly, ct).ConfigureAwait(continueOnCapturedContext: false));
	}
}
