using Godot;
using System.IO;

namespace Theriapolis.GodotHost.Platform;

/// <summary>
/// Single source of truth for resolving the project's Content/ directory.
/// Content lives at the repository root (sibling to Theriapolis.Godot/),
/// not inside res://. This avoids duplicating gigabytes of game data, and
/// keeps the same Content/Data and Content/Gfx tree the MonoGame branch
/// and headless Tools all read from.
///
/// Resolution walks up from res:// looking for Content/Data; once found,
/// the parent of Data is the Content root, used for Gfx too. Cached after
/// first hit so repeated calls are cheap.
/// </summary>
public static class ContentPaths
{
    private static string? _cachedContentRoot;

    public static string ContentRoot => _cachedContentRoot ??= ResolveContentRoot();
    public static string DataDir => Path.Combine(ContentRoot, "Data");
    public static string GfxDir  => Path.Combine(ContentRoot, "Gfx");

    private static string ResolveContentRoot()
    {
        // Try res://../Content first — the canonical layout.
        string fromRes = ProjectSettings.GlobalizePath("res://../Content");
        if (Directory.Exists(Path.Combine(fromRes, "Data"))) return fromRes;

        // Walk up further in case Theriapolis.Godot is nested deeper.
        string? dir = ProjectSettings.GlobalizePath("res://").TrimEnd('/', '\\');
        for (int i = 0; i < 6; i++)
        {
            if (string.IsNullOrEmpty(dir)) break;
            string candidate = Path.Combine(dir, "Content");
            if (Directory.Exists(Path.Combine(candidate, "Data"))) return candidate;
            dir = Path.GetDirectoryName(dir);
        }

        // Last resort — return the canonical path even if it doesn't exist;
        // callers that care will fail with a useful error.
        GD.PushWarning($"[ContentPaths] Content root not found; using {fromRes}");
        return fromRes;
    }
}
