namespace NeonSprawl.Server.Game.Skills;

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

        return null;
    }

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

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

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

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

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