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

namespace NeonSprawl.Server.Game.Npc;

/// <summary>Loads and validates <c>content/npc-behaviors/*_npc_behaviors.json</c> using the same rules as <c>scripts/validate_content.py</c> (NEO-88).</summary>
public static class NpcBehaviorDefinitionCatalogLoader
{
    /// <summary>Loads catalogs from disk or throws <see cref="InvalidOperationException"/> with actionable messages.</summary>
    public static NpcBehaviorDefinitionCatalog Load(string npcBehaviorsDirectory, string schemaPath, ILogger logger)
    {
        npcBehaviorsDirectory = Path.GetFullPath(npcBehaviorsDirectory);
        schemaPath = Path.GetFullPath(schemaPath);

        var errors = new List<string>();

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

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

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

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

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

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

        var behaviorIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
        var rows = new Dictionary<string, NpcBehaviorDefRow>(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 npcBehaviorsNode = rootObj["npcBehaviors"];
            if (npcBehaviorsNode is not JsonArray npcBehaviorsArray)
            {
                errors.Add($"error: {path}: expected top-level 'npcBehaviors' array");
                continue;
            }

            for (var i = 0; i < npcBehaviorsArray.Count; i++)
            {
                var behavior = npcBehaviorsArray[i];
                if (behavior is not JsonObject rowObj)
                {
                    errors.Add($"error: {path}: npcBehaviors[{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} npcBehaviors[{i}] (root): schema validation failed");

                    errors.AddRange(schemaMsgs);
                }

                var rowSchemaErrors = schemaMsgs.Count;

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

                    behaviorIdToSourceFile[bid] = path;
                    rows[bid] = ParseRow(rowObj);
                }
            }
        }

        ThrowIfAny(errors);

        var e5m2 = PrototypeE5M2NpcBehaviorCatalogRules.TryGetE5M2GateError(behaviorIdToSourceFile);
        if (e5m2 is not null)
        {
            errors.Add(e5m2);
            ThrowIfAny(errors);
        }

        var numeric = PrototypeE5M2NpcBehaviorCatalogRules.TryGetNumericGateError(rows);
        if (numeric is not null)
        {
            errors.Add(numeric);
            ThrowIfAny(errors);
        }

        if (logger.IsEnabled(LogLevel.Information))
        {
            logger.LogInformation(
                "Loaded NPC behavior catalog from {NpcBehaviorsDirectory}: {BehaviorCount} behavior(s) across {CatalogFileCount} JSON catalog file(s).",
                npcBehaviorsDirectory,
                rows.Count,
                jsonFiles.Length);
        }

        return new NpcBehaviorDefinitionCatalog(npcBehaviorsDirectory, rows, jsonFiles.Length);
    }

    private static NpcBehaviorDefRow ParseRow(JsonObject rowObj)
    {
        var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
        var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
        var archetypeKind = (rowObj["archetypeKind"] as JsonValue)!.GetValue<string>();
        var maxHp = (rowObj["maxHp"] as JsonValue)!.GetValue<int>();
        var aggroRadius = (rowObj["aggroRadius"] as JsonValue)!.GetValue<double>();
        var leashRadius = (rowObj["leashRadius"] as JsonValue)!.GetValue<double>();
        var telegraphWindupSeconds = (rowObj["telegraphWindupSeconds"] as JsonValue)!.GetValue<double>();
        var attackDamage = (rowObj["attackDamage"] as JsonValue)!.GetValue<int>();
        var attackCooldownSeconds = (rowObj["attackCooldownSeconds"] as JsonValue)!.GetValue<double>();

        return new NpcBehaviorDefRow(
            id,
            displayName,
            archetypeKind,
            maxHp,
            aggroRadius,
            leashRadius,
            telegraphWindupSeconds,
            attackDamage,
            attackCooldownSeconds);
    }

    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} npcBehaviors[{index}] {loc}: {kv.Key} — {kv.Value}");
        }
    }

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

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

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