namespace NeonSprawl.Server.Game.Combat;

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

        return null;
    }

    /// <summary>
    /// Resolves the abilities catalog directory.
    /// Empty <paramref name="configuredAbilitiesDirectory"/> triggers discovery from <see cref="AppContext.BaseDirectory"/>.
    /// </summary>
    public static string ResolveAbilitiesDirectory(string? configuredAbilitiesDirectory, string contentRootPath)
    {
        if (string.IsNullOrWhiteSpace(configuredAbilitiesDirectory))
        {
            var discovered = TryDiscoverAbilitiesDirectory(AppContext.BaseDirectory);
            if (discovered is not null)
                return discovered;

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

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

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

    /// <summary>Resolves JSON Schema path for a single ability row (Draft 2020-12).</summary>
    public static string ResolveAbilityDefSchemaPath(
        string abilitiesDirectory,
        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(abilitiesDirectory, "..", "schemas", "ability-def.schema.json"));
    }
}
