using NUnit.Framework;
using UnityEngine;
using UnityEditor;
using System.IO;
using LLM.Editor.Analysis;

namespace LLM.Editor.Tests.Unit
{
    [TestFixture]
    public class SourceCodeProviderTests
    {
        private const string TestScriptName = "TestSourceCodeProviderScript.cs";
        private const string TestScriptContent = "public class TestSourceCodeProviderScript {}";
        private string _testScriptPath;

        [SetUp]
        public void SetUp()
        {
            _testScriptPath = Path.Combine(Application.dataPath, TestScriptName);
            File.WriteAllText(_testScriptPath, TestScriptContent);
            AssetDatabase.Refresh();
        }

        [TearDown]
        public void TearDown()
        {
            if (File.Exists(_testScriptPath))
            {
                File.Delete(_testScriptPath);
                File.Delete(_testScriptPath + ".meta");
                AssetDatabase.Refresh();
            }
        }

        [Test]
        public void GetContext_WithValidMonoScript_ReturnsFileContent()
        {
            // Arrange
            var provider = new SourceCodeProvider();
            var scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>($"Assets/{TestScriptName}");
            Assume.That(scriptAsset, Is.Not.Null, "Setup failed: Could not load test script asset.");

            // Act
            var context = provider.GetContext(scriptAsset, null);

            // Assert
            Assert.IsInstanceOf<string>(context);
            Assert.AreEqual(TestScriptContent, context);
        }

        [Test]
        public void GetContext_WithNonScriptAsset_ReturnsError()
        {
            // Arrange
            var provider = new SourceCodeProvider();
            var material = new Material(Shader.Find("Standard")); // Create a non-script asset

            // Act
            var context = provider.GetContext(material, null);

            // Assert
            Assert.IsInstanceOf<string>(context);
            Assert.IsTrue(((string)context).StartsWith("Error: Target must be a MonoScript"));
        }

        [Test]
        public void GetContext_WithNullTarget_ReturnsError()
        {
            // Arrange
            var provider = new SourceCodeProvider();

            // Act
            var context = provider.GetContext(null, null);

            // Assert
            Assert.IsInstanceOf<string>(context);
            Assert.IsTrue(((string)context).StartsWith("Error: Target must be a MonoScript"));
        }
    }
}
