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

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

        private static readonly string[] AllowedRuntimeShaderFindFiles = {
            "Assets/Eagle/BeastMaterialCompatibility.cs",
        };

        [Test]
        public void ProjectOwnedRuntimeScriptsDoNotFindShadersByName() {
            var violations = new List<string>();

            foreach (var scriptPath in ProjectOwnedRuntimeScriptPaths()) {
                var lines = File.ReadAllLines(scriptPath);
                for (var i = 0; i < lines.Length; i++) {
                    if (!lines[i].Contains("Shader.Find")) { continue; }

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

            Assert.IsEmpty(
                    violations,
                    "Project-owned Eagle/Shardok runtime-created materials should use serialized shader/material references. " +
                            "Unity/URP-provided shader lookup is allowed only in documented compatibility shims:\n" +
                            string.Join("\n", violations));
        }

        private static IEnumerable<string> ProjectOwnedRuntimeScriptPaths() {
            return AssetDatabase.GetAllAssetPaths()
                    .Where(path => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase))
                    .Where(path => ProjectRuntimeScriptRoots.Any(
                                   root => path.StartsWith(root, StringComparison.Ordinal)))
                    .Where(path => path.IndexOf("/Editor/", StringComparison.Ordinal) < 0)
                    .Where(path => !AllowedRuntimeShaderFindFiles.Contains(path))
                    .OrderBy(path => path, StringComparer.Ordinal);
        }
    }
}
