using Godot;
using System.IO;
using System.Linq;

namespace Theriapolis.GodotHost.Platform;

/// <summary>
/// M3 asset pipeline smoke test. Walks Content/Data and Content/Gfx,
/// reports counts, and verifies every PNG under Gfx loads via
/// ContentLoader. Exits non-zero on any failure.
///
/// Run with:
///   godot --headless --path Theriapolis.Godot -- --asset-test
/// </summary>
public static class AssetTest
{
    public static int Run()
    {
        GD.Print($"[asset-test] Content root: {ContentPaths.ContentRoot}");
        GD.Print($"[asset-test] Data dir:     {ContentPaths.DataDir}");
        GD.Print($"[asset-test] Gfx dir:      {ContentPaths.GfxDir}");

        if (!Directory.Exists(ContentPaths.DataDir))
        {
            GD.PrintErr($"[asset-test] FAIL: Data directory missing");
            return 1;
        }
        if (!Directory.Exists(ContentPaths.GfxDir))
        {
            GD.PrintErr($"[asset-test] FAIL: Gfx directory missing");
            return 1;
        }

        var jsonFiles = Directory.GetFiles(ContentPaths.DataDir, "*.json", SearchOption.AllDirectories);
        GD.Print($"[asset-test] Data: {jsonFiles.Length} JSON files");

        var pngFiles = Directory.GetFiles(ContentPaths.GfxDir, "*.png", SearchOption.AllDirectories);
        GD.Print($"[asset-test] Gfx:  {pngFiles.Length} PNG files");

        int loaded = 0;
        int failed = 0;
        foreach (var absolute in pngFiles)
        {
            string relative = Path.GetRelativePath(ContentPaths.GfxDir, absolute)
                                  .Replace('\\', '/');
            var tex = ContentLoader.LoadGfx(relative);
            if (tex is null)
            {
                failed++;
            }
            else
            {
                loaded++;
            }
        }

        GD.Print($"[asset-test] Loaded {loaded}/{pngFiles.Length} PNGs " +
                 $"(cache size {ContentLoader.CacheCount}, failed {failed})");

        if (failed > 0)
        {
            GD.PrintErr($"[asset-test] FAIL: {failed} texture(s) failed to load");
            return 1;
        }

        // Also report the sub-tree breakdown, matching what M4 will care about
        var bySubdir = pngFiles
            .GroupBy(f => Path.GetRelativePath(ContentPaths.GfxDir, Path.GetDirectoryName(f)!)
                              .Replace('\\', '/'))
            .OrderBy(g => g.Key);
        GD.Print($"[asset-test] PNG breakdown by sub-directory:");
        foreach (var g in bySubdir)
            GD.Print($"[asset-test]   {g.Key,-24} {g.Count(),3} files");

        GD.Print($"[asset-test] OK");
        return 0;
    }
}
