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

namespace NeonSprawl.Server.Game.Crafting;

/// <summary>Loads and validates <c>content/recipes/*_recipes.json</c> using the same rules as <c>scripts/validate_content.py</c> (NEO-66).</summary>
public static class RecipeDefinitionCatalogLoader
{
    /// <summary>Loads catalogs from disk or throws <see cref="InvalidOperationException"/> with actionable messages.</summary>
    public static RecipeDefinitionCatalog Load(
        string recipesDirectory,
        string recipeDefSchemaPath,
        string recipeIoRowSchemaPath,
        IReadOnlySet<string> knownItemIds,
        IReadOnlySet<string> knownSkillIds,
        ILogger logger)
    {
        recipesDirectory = Path.GetFullPath(recipesDirectory);
        recipeDefSchemaPath = Path.GetFullPath(recipeDefSchemaPath);
        recipeIoRowSchemaPath = Path.GetFullPath(recipeIoRowSchemaPath);

        var errors = new List<string>();

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

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

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

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

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

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

        var ioSchemaText = File.ReadAllText(recipeIoRowSchemaPath);
        var defSchemaText = File.ReadAllText(recipeDefSchemaPath);
        var ioSchema = JsonSchema.FromText(ioSchemaText);
        SchemaRegistry.Global.Register(ioSchema);
        var defSchema = JsonSchema.FromText(defSchemaText);
        SchemaRegistry.Global.Register(defSchema);

        var evalOptions = new EvaluationOptions { OutputFormat = OutputFormat.List };

        var recipeIdToSourceFile = new Dictionary<string, string>(StringComparer.Ordinal);
        var idToRecipeKind = new Dictionary<string, string>(StringComparer.Ordinal);
        var idToRequiredSkillId = new Dictionary<string, string>(StringComparer.Ordinal);
        var rows = new Dictionary<string, RecipeDefRow>(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 recipesNode = rootObj["recipes"];
            if (recipesNode is not JsonArray recipesArray)
            {
                errors.Add($"error: {path}: expected top-level 'recipes' array");
                continue;
            }

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

                var eval = defSchema.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} recipes[{i}] (root): schema validation failed");

                    errors.AddRange(schemaMsgs);
                }

                var rowSchemaErrors = schemaMsgs.Count;

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

                    recipeIdToSourceFile[rid] = path;

                    var recipeKind = (rowObj["recipeKind"] as JsonValue)?.GetValue<string>();
                    if (recipeKind is not null)
                        idToRecipeKind[rid] = recipeKind;

                    var requiredSkillId = (rowObj["requiredSkillId"] as JsonValue)?.GetValue<string>();
                    if (requiredSkillId is not null)
                    {
                        idToRequiredSkillId[rid] = requiredSkillId;
                        if (!knownSkillIds.Contains(requiredSkillId))
                        {
                            errors.Add(
                                $"error: {path} recipes[{i}]: requiredSkillId '{requiredSkillId}' " +
                                $"is not a known SkillDef id (known: [{string.Join(", ", knownSkillIds.Order(StringComparer.Ordinal).Select(s => "'" + s + "'"))}])");
                        }
                    }

                    CrossCheckIoRows(rowObj, path, i, "inputs", knownItemIds, errors);
                    CrossCheckIoRows(rowObj, path, i, "outputs", knownItemIds, errors);

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

        ThrowIfAny(errors);

        var slice3 = PrototypeSlice3RecipeCatalogRules.TryGetSlice3GateError(
            recipeIdToSourceFile,
            idToRecipeKind,
            idToRequiredSkillId);
        if (slice3 is not null)
        {
            errors.Add(slice3);
            ThrowIfAny(errors);
        }

        if (logger.IsEnabled(LogLevel.Information))
        {
            logger.LogInformation(
                "Loaded recipe catalog from {RecipesDirectory}: {RecipeCount} recipe(s) across {CatalogFileCount} JSON catalog file(s).",
                recipesDirectory,
                rows.Count,
                jsonFiles.Length);
        }

        return new RecipeDefinitionCatalog(recipesDirectory, rows, jsonFiles.Length);
    }

    private static void CrossCheckIoRows(
        JsonObject rowObj,
        string path,
        int recipeIndex,
        string ioKey,
        IReadOnlySet<string> knownItemIds,
        List<string> errors)
    {
        if (rowObj[ioKey] is not JsonArray ioArray)
            return;

        for (var j = 0; j < ioArray.Count; j++)
        {
            if (ioArray[j] is not JsonObject ioRow)
                continue;

            var itemId = (ioRow["itemId"] as JsonValue)?.GetValue<string>();
            if (itemId is not null && !knownItemIds.Contains(itemId))
            {
                errors.Add(
                    $"error: {path} recipes[{recipeIndex}].{ioKey}[{j}]: itemId '{itemId}' is not in item catalogs");
            }
        }
    }

    private static RecipeDefRow ParseRow(JsonObject rowObj)
    {
        var id = (rowObj["id"] as JsonValue)!.GetValue<string>();
        var displayName = (rowObj["displayName"] as JsonValue)!.GetValue<string>();
        var recipeKind = (rowObj["recipeKind"] as JsonValue)!.GetValue<string>();
        var requiredSkillId = (rowObj["requiredSkillId"] as JsonValue)!.GetValue<string>();
        var inputs = ParseIoRows(rowObj["inputs"] as JsonArray);
        var outputs = ParseIoRows(rowObj["outputs"] as JsonArray);

        int? requiredSkillLevel = null;
        if (rowObj["requiredSkillLevel"] is JsonValue levelValue &&
            levelValue.TryGetValue<int>(out var level))
        {
            requiredSkillLevel = level;
        }

        string? stationTag = null;
        if (rowObj["stationTag"] is JsonValue stationTagValue)
            stationTag = stationTagValue.GetValue<string>();

        return new RecipeDefRow(id, displayName, recipeKind, requiredSkillId, inputs, outputs, requiredSkillLevel, stationTag);
    }

    private static IReadOnlyList<RecipeIoRow> ParseIoRows(JsonArray? array)
    {
        if (array is null)
            return [];

        var rows = new List<RecipeIoRow>(array.Count);
        foreach (var node in array)
        {
            if (node is not JsonObject ioObj)
                continue;

            var itemId = (ioObj["itemId"] as JsonValue)!.GetValue<string>();
            var quantity = (ioObj["quantity"] as JsonValue)!.GetValue<int>();
            rows.Add(new RecipeIoRow(itemId, quantity));
        }

        return rows;
    }

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

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

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

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