namespace NeonSprawl.Server.Game.Npc;

/// <summary>Resolves NPC behavior catalog paths for local dev, tests, and container layouts (NEO-88).</summary>
public static class NpcBehaviorCatalogPathResolution
{
    /// <summary>Walks <paramref name="startDirectory"/> and parents for an existing <c>content/npc-behaviors</c> directory.</summary>
    public static string? TryDiscoverNpcBehaviorsDirectory(string startDirectory)
    {
        for (var dir = new DirectoryInfo(startDirectory); dir is not null; dir = dir.Parent)
        {
            var candidate = Path.Combine(dir.FullName, "content", "npc-behaviors");
            if (Directory.Exists(candidate))
                return Path.GetFullPath(candidate);
        }

        return null;
    }

    /// <summary>
    /// Resolves the npc-behaviors catalog directory.
    /// Empty <paramref name="configuredNpcBehaviorsDirectory"/> triggers discovery from <see cref="AppContext.BaseDirectory"/>.
    /// </summary>
    public static string ResolveNpcBehaviorsDirectory(string? configuredNpcBehaviorsDirectory, string contentRootPath)
    {
        if (string.IsNullOrWhiteSpace(configuredNpcBehaviorsDirectory))
        {
            var discovered = TryDiscoverNpcBehaviorsDirectory(AppContext.BaseDirectory);
            if (discovered is not null)
                return discovered;

            throw new InvalidOperationException(
                "Content:NpcBehaviorsDirectory is not set and auto-discovery failed (no ancestor of AppContext.BaseDirectory contains 'content/npc-behaviors'). " +
                "Set Content:NpcBehaviorsDirectory in configuration or environment (e.g. Content__NpcBehaviorsDirectory).");
        }

        var trimmed = configuredNpcBehaviorsDirectory.Trim();
        if (Path.IsPathRooted(trimmed))
            return Path.GetFullPath(trimmed);

        return Path.GetFullPath(Path.Combine(contentRootPath, trimmed));
    }

    /// <summary>Resolves JSON Schema path for a single NPC behavior row (Draft 2020-12).</summary>
    public static string ResolveNpcBehaviorDefSchemaPath(
        string npcBehaviorsDirectory,
        string? configuredSchemaPath,
        string contentRootPath)
    {
        if (!string.IsNullOrWhiteSpace(configuredSchemaPath))
        {
            var trimmed = configuredSchemaPath.Trim();
            if (Path.IsPathRooted(trimmed))
                return Path.GetFullPath(trimmed);

            return Path.GetFullPath(Path.Combine(contentRootPath, trimmed));
        }

        return Path.GetFullPath(Path.Combine(npcBehaviorsDirectory, "..", "schemas", "npc-behavior-def.schema.json"));
    }
}
