using System;
using System.Collections.Generic;
using System.Linq;
namespace AIRuntime.Runtime.Capabilities
{
    /// <summary>
    /// Stores all tools available to the Harness.
    /// Responsible only for registration and lookup.
    /// </summary>
    public class CapabilityRegistry
    {
        private readonly Dictionary<string, ICapability> _tools = new();

        /// <summary>
        /// Registers a tool with the registry.
        /// </summary>
        public void Register(ICapability capability)
        {
            if (capability == null)
                throw new ArgumentNullException(nameof(capability));

            if (string.IsNullOrWhiteSpace(capability.Name))
                throw new ArgumentException("Tool name cannot be empty.");

            if (_tools.ContainsKey(capability.Name))
                throw new InvalidOperationException(
                    $"Tool '{capability.Name}' is already registered.");

            _tools.Add(capability.Name, capability);
        }

        /// <summary>
        /// Removes a tool.
        /// </summary>
        public bool Unregister(string toolName)
        {
            return _tools.Remove(toolName);
        }

        /// <summary>
        /// Returns true if the tool exists.
        /// </summary>
        public bool Contains(string toolName)
        {
            return _tools.ContainsKey(toolName);
        }

        /// <summary>
        /// Gets a tool by name.
        /// Throws if the tool doesn't exist.
        /// </summary>
        public ICapability Get(string toolName)
        {
            if (!_tools.TryGetValue(toolName, out var tool))
                throw new KeyNotFoundException(
                    $"Tool '{toolName}' is not registered.");

            return tool;
        }

        /// <summary>
        /// Returns all registered tools.
        /// </summary>
        public IReadOnlyCollection<ICapability> GetAll()
        {
            return _tools.Values;
        }

        /// <summary>
        /// Removes every registered tool.
        /// </summary>
        public void Clear()
        {
            _tools.Clear();
        }
        /// <summary>
        /// Returns descriptions of all registered capabilities.
        /// </summary>
        public IReadOnlyList<CapabilityDescriptor> GetDescriptors()
        {
            CapabilitySchemaExporter exporter =
                new CapabilitySchemaExporter();


            return _tools.Values
                .Select(capability =>
                    new CapabilityDescriptor(
                        capability.Name,
                        capability.Description,
                        exporter.Export(capability)))
                .ToList();
        }

        /// <summary>
        /// Number of registered tools.
        /// </summary>
        public int Count => _tools.Count;
    }
}