namespace NeonSprawl.Server.Game.Mastery;

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

        return null;
    }

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

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

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

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

    /// <summary>Resolves JSON Schema path for a mastery catalog document (Draft 2020-12).</summary>
    public static string ResolveMasteryCatalogSchemaPath(
        string masteryDirectory,
        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(masteryDirectory, "..", "schemas", "mastery-catalog.schema.json"));
    }
}
