using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Json.Schema;
using Microsoft.Extensions.Logging;

namespace NeonSprawl.Server.Game.Items;

/// <summary>Loads and validates <c>content/items/*_items.json</c> using the same rules as <c>scripts/validate_content.py</c> (NEO-51).</summary>
public static class ItemDefinitionCatalogLoader
{
    /// <summary>Loads catalogs from disk or throws <see cref="InvalidOperationException"/> with actionable messages.</summary>
    public static ItemDefinitionCatalog Load(string itemsDirectory, string schemaPath, ILogger logger)
    {
        itemsDirectory = Path.GetFullPath(itemsDirectory);
        schemaPath = Path.GetFullPath(schemaPath);

        var errors = new List<string>();

        if (!File.Exists(schemaPath))
            errors.Add($"error: missing schema file {schemaPath}");

        if (!Directory.Exists(itemsDirectory))
            errors.Add($"error: missing directory {itemsDirectory}");

        if (errors.Count > 0)
            ThrowIfAny(errors);

        var jsonFiles = Directory.GetFiles(itemsDirectory, "*_items.json", SearchOption.TopDirectoryOnly)
            .OrderBy(p => p, StringComparer.Ordinal)
            .ToArray();
        if (jsonFiles.Length == 0)
            errors.Add($"error: no *_items.json files under {itemsDirectory}");

        if (errors.Count > 0)
            ThrowIfAny(errors);

        var schema = JsonSchema.FromText(File.ReadAllText(schemaPath));
        var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };

        var itemIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
        var idToRole = new Dictionary<string, string>(StringComparer.Ordinal);
        var idToSlotKind = new Dictionary<string, string>(StringComparer.Ordinal);
        var idToStackMax = new Dictionary<string, int>(StringComparer.Ordinal);
        var rows = new Dictionary<string, ItemDefRow>(StringComparer.Ordinal);

        foreach (var path in jsonFiles)
        {
            JsonNode? root;
            try
            {
                root = JsonNode.Parse(File.ReadAllText(path));
            }
            catch (JsonException ex)
            {
                errors.Add($"error: {path}: invalid JSON: {ex.Message}");
                continue;
            }

            if (root is not JsonObject rootObj)
            {
                errors.Add($"error: {path}: expected JSON object at root");
                continue;
            }

            var schemaVersionNode = rootObj["schemaVersion"];
            if (schemaVersionNode is not JsonValue schemaVersionValue ||
                !schemaVersionValue.TryGetValue<int>(out var schemaVersion) ||
                schemaVersion != 1)
            {
                var got = schemaVersionNode?.ToJsonString() ?? "null";
                errors.Add($"error: {path}: expected schemaVersion 1, got {got}");
                continue;
            }

            var itemsNode = rootObj["items"];
            if (itemsNode is not JsonArray itemsArray)
            {
                errors.Add($"error: {path}: expected top-level 'items' array");
                continue;
            }

            for (var i = 0; i < itemsArray.Count; i++)
            {
                var item = itemsArray[i];
                if (item is not JsonObject rowObj)
                {
                    errors.Add($"error: {path}: items[{i}] must be an object");
                    continue;
                }

                var eval = schema.Evaluate(rowObj, evalOptions);
                var schemaMsgs = CollectSchemaMessages(eval, path, i).OrderBy(m => m, StringComparer.Ordinal).ToList();
                if (!eval.IsValid)
                {
                    if (schemaMsgs.Count == 0)
                        schemaMsgs.Add($"error: {path} items[{i}] (root): schema validation failed");

                    errors.AddRange(schemaMsgs);
                }

                var rowSchemaErrors = schemaMsgs.Count;

                var iid = (rowObj["id"] as JsonValue)?.GetValue<string>();
                if (iid is not null && rowSchemaErrors == 0)
                {
                    if (itemIdToSourceFile.TryGetValue(iid, out var prevPath))
                    {
                        errors.Add($"error: duplicate item id '{iid}' in {prevPath} and {path}");
                        continue;
                    }

                    itemIdToSourceFile[iid] = path;

                    var role = (rowObj["prototypeRole"] as JsonValue)?.GetValue<string>();
                    if (role is not null)
                        idToRole[iid] = role;

                    var slotKind = (rowObj["inventorySlotKind"] as JsonValue)?.GetValue<string>();
                    if (slotKind is not null)
                        idToSlotKind[iid] = slotKind;

                    if (rowObj["stackMax"] is JsonValue stackMaxValue &&
                        stackMaxValue.TryGetValue<int>(out var stackMax))
                    {
                        idToStackMax[iid] = stackMax;
                    }

                    rows[iid] = ParseRow(rowObj);
                }
            }
        }

        ThrowIfAny(errors);

        var slice1 = PrototypeSlice1ItemCatalogRules.TryGetSlice1GateError(
            itemIdToSourceFile,
            idToRole,
            idToSlotKind,
            idToStackMax);
        if (slice1 is not null)
        {
            errors.Add(slice1);
            ThrowIfAny(errors);
        }

        if (logger.IsEnabled(LogLevel.Information))
        {
            logger.LogInformation(
                "Loaded item catalog from {ItemsDirectory}: {ItemCount} item(s) across {CatalogFileCount} JSON catalog file(s).",
                itemsDirectory,
                rows.Count,
                jsonFiles.Length);
        }

        return new ItemDefinitionCatalog(itemsDirectory, rows, jsonFiles.Length);
    }

    private static ItemDefRow ParseRow(JsonObject rowObj)
    {
        var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
        var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
        var prototypeRole = (rowObj["prototypeRole"] as JsonValue)!.GetValue<string>();
        var stackMax = (rowObj["stackMax"] as JsonValue)!.GetValue<int>();
        var inventorySlotKind = (rowObj["inventorySlotKind"] as JsonValue)!.GetValue<string>();
        string? rarity = null;
        if (rowObj["rarity"] is JsonValue rarityValue)
            rarity = rarityValue.GetValue<string>();
        string? bindPolicy = null;
        if (rowObj["bindPolicy"] is JsonValue bindPolicyValue)
            bindPolicy = bindPolicyValue.GetValue<string>();
        int? durabilityMax = null;
        if (rowObj["durabilityMax"] is JsonValue durabilityMaxValue &&
            durabilityMaxValue.TryGetValue<int>(out var dmax))
        {
            durabilityMax = dmax;
        }

        return new ItemDefRow(id, displayName, prototypeRole, stackMax, inventorySlotKind, rarity, bindPolicy, durabilityMax);
    }

    private static List<string> CollectSchemaMessages(EvaluationResults eval, string filePath, int index)
    {
        var sink = new List<string>();
        AppendSchemaMessages(eval, filePath, index, sink);
        return sink;
    }

    private static void AppendSchemaMessages(EvaluationResults r, string filePath, int index, List<string> sink)
    {
        if (r.HasDetails)
        {
            foreach (var d in r.Details!)
                AppendSchemaMessages(d, filePath, index, sink);
        }

        if (!r.HasErrors)
            return;

        foreach (var kv in r.Errors!)
        {
            var loc = r.InstanceLocation?.ToString();
            if (string.IsNullOrEmpty(loc) || loc == "#")
                loc = "(root)";

            sink.Add($"error: {filePath} items[{index}] {loc}: {kv.Key} — {kv.Value}");
        }
    }

    private static void ThrowIfAny(List<string> errors)
    {
        if (errors.Count == 0)
            return;

        var sb = new StringBuilder();
        sb.AppendLine("Item catalog validation failed:");
        foreach (var e in errors.OrderBy(x => x, StringComparer.Ordinal))
            sb.AppendLine(e);

        throw new InvalidOperationException(sb.ToString().TrimEnd());
    }
}
