namespace NeonSprawl.Server.Game.Items;

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

        return null;
    }

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

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

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

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

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