using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using UnityEditor;

namespace eagle0.Tests {
    [TestFixture]
    public class ProjectShaderPatternTests {
        private static readonly string[] ProjectShaderRoots = {
            "Assets/Eagle",
            "Assets/Shardok",
        };

        private static readonly string[] BuiltInOnlyPatterns = {
            "GrabPass",
            "#pragma surface",
            "UnityCG.cginc",
            "UnityUI.cginc",
            "UNITY_MATRIX_",
            "sampler2D _GrabTexture",
            "tessell",
            "Tessellation",
        };

        [Test]
        public void ProjectOwnedEagleAndShardokShadersDoNotUseBuiltInOnlyPatterns() {
            var violations = new List<string>();
            foreach (var shaderPath in ProjectOwnedShaderPaths()) {
                var lines = File.ReadAllLines(shaderPath);
                for (var i = 0; i < lines.Length; i++) {
                    foreach (var pattern in BuiltInOnlyPatterns) {
                        if (lines[i].IndexOf(pattern, StringComparison.OrdinalIgnoreCase) < 0) {
                            continue;
                        }

                        violations.Add($"{shaderPath}:{i + 1}: {pattern}: {lines[i].Trim()}");
                    }
                }
            }

            Assert.IsEmpty(
                    violations,
                    "Project-owned Eagle/Shardok shaders should stay URP-compatible:\n" +
                            string.Join("\n", violations));
        }

        private static IEnumerable<string> ProjectOwnedShaderPaths() {
            return AssetDatabase.GetAllAssetPaths()
                    .Where(path => path.EndsWith(".shader", StringComparison.OrdinalIgnoreCase))
                    .Where(path => ProjectShaderRoots.Any(
                                   root => path.StartsWith(root, StringComparison.Ordinal)))
                    .OrderBy(path => path, StringComparer.Ordinal);
        }
    }
}
