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

namespace NeonSprawl.Server.Game.Combat;

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

        var errors = new List<string>();

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

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

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

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

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

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

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

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

                    errors.AddRange(schemaMsgs);
                }

                var rowSchemaErrors = schemaMsgs.Count;

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

                    abilityIdToSourceFile[aid] = path;
                    rows[aid] = ParseRow(rowObj);
                }
            }
        }

        ThrowIfAny(errors);

        var e5m1 = PrototypeE5M1AbilityCatalogRules.TryGetE5M1GateError(abilityIdToSourceFile);
        if (e5m1 is not null)
        {
            errors.Add(e5m1);
            ThrowIfAny(errors);
        }

        if (logger.IsEnabled(LogLevel.Information))
        {
            logger.LogInformation(
                "Loaded ability catalog from {AbilitiesDirectory}: {AbilityCount} ability(s) across {CatalogFileCount} JSON catalog file(s).",
                abilitiesDirectory,
                rows.Count,
                jsonFiles.Length);
        }

        return new AbilityDefinitionCatalog(abilitiesDirectory, rows, jsonFiles.Length);
    }

    private static AbilityDefRow ParseRow(JsonObject rowObj)
    {
        var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
        var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
        var baseDamage = (rowObj["baseDamage"] as JsonValue)!.GetValue<int>();
        var cooldownSeconds = (rowObj["cooldownSeconds"] as JsonValue)!.GetValue<double>();
        string? abilityKind = null;
        if (rowObj["abilityKind"] is JsonValue abilityKindValue)
            abilityKind = abilityKindValue.GetValue<string>();

        return new AbilityDefRow(id, displayName, baseDamage, cooldownSeconds, abilityKind);
    }

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

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

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

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