using System;
using System.Collections.Generic;
using System.Linq;
using AssetBank.Editor.SchemaConverter.Data.Input;
using Newtonsoft.Json.Linq;

namespace AssetBank.Editor.SchemaConverter.Processors
{
    /// <summary>
    /// Handles the logic for extracting scene-level settings data.
    /// </summary>
    public static class SceneDataProcessor
    {
        /// <summary>
        /// Filters for scene-level nodes and extracts their data.
        /// </summary>
        /// <param name="allNodes">The complete list of original nodes from the JSON.</param>
        /// <param name="consumedAnchorIds">A set of all anchor_ids that have already been processed as part of the hierarchy or as prefabs.</param>
        /// <returns>A JObject containing all scene-level data, keyed by the component name.</returns>
        public static JObject Process(IReadOnlyList<OriginalNode> allNodes, HashSet<string> consumedAnchorIds)
        {
            var sceneData = new JObject();

            // A node is a scene setting if it was not consumed by the hierarchy/prefab processors.
            var sceneNodes = allNodes.Where(node => !consumedAnchorIds.Contains(node.anchor_id));

            foreach (var node in sceneNodes)
            {
                if (node.data is not { HasValues: true }) continue;

                // Take the first property from the 'data' object (e.g., "LightmapSettings").
                var settingProperty = node.data.Properties().FirstOrDefault();
                if (settingProperty != null)
                {
                    try
                    {
                        // Add it to our scene_data object.
                        sceneData.Add(settingProperty);
                    }
                    catch (ArgumentException)
                    {
                        // Provide a detailed error message upon failure.
                        var existingKeys = string.Join(", ", sceneData.Properties().Select(p => p.Name));
                        throw new ArgumentException($"Duplicate key error in SceneDataProcessor. Attempted to add key '{settingProperty.Name}' (from anchor_id: {node.anchor_id}) but a property with that name already exists. Existing keys: [{existingKeys}]");
                    }
                }
            }

            return sceneData;
        }
    }
}