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

namespace NeonSprawl.Server.Game.Skills;

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

        var errors = new List<string>();

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

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

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

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

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

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

        var skillIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
        var skillIdToCategory = new Dictionary<string, string>(StringComparer.Ordinal);
        var rows = new Dictionary<string, SkillDefRow>(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;
            }

            var skillsNode = root?["skills"];
            if (skillsNode is not JsonArray skillsArray)
            {
                errors.Add($"error: {path}: expected top-level 'skills' array");
                continue;
            }

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

                    errors.AddRange(schemaMsgs);
                }

                var rowSchemaErrors = schemaMsgs.Count;

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

                    skillIdToSourceFile[sid] = path;

                    var category = (rowObj["category"] as JsonValue)?.GetValue<string>();
                    if (category is not null)
                        skillIdToCategory[sid] = category;

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

        ThrowIfAny(errors);

        var slice1 = PrototypeSlice1SkillCatalogRules.TryGetSlice1GateError(skillIdToSourceFile, skillIdToCategory);
        if (slice1 is not null)
        {
            errors.Add(slice1);
            ThrowIfAny(errors);
        }

        logger.LogInformation(
            "Loaded skill catalog from {SkillsDirectory}: {SkillCount} skill(s) across {CatalogFileCount} JSON catalog file(s).",
            skillsDirectory,
            rows.Count,
            jsonFiles.Length);

        return new SkillDefinitionCatalog(skillsDirectory, rows, jsonFiles.Length);
    }

    private static SkillDefRow ParseRow(JsonObject rowObj)
    {
        var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
        var category = (rowObj["category"] as JsonValue)!.GetValue<string>();
        var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
        var kindsArray = rowObj["allowedXpSourceKinds"] as JsonArray
                         ?? throw new InvalidOperationException("allowedXpSourceKinds missing");
        var kinds = new List<string>();
        foreach (var n in kindsArray)
        {
            if (n is JsonValue v)
                kinds.Add(v.GetValue<string>());
        }

        return new SkillDefRow(id, category, displayName, kinds);
    }

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

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

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

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