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

namespace LLM.Editor.Tests.Unit
{
    [TestFixture]
    public class DirectoryStructureProviderTests
    {
        private static string TestRoot => Path.Combine(TestConstants.TestPath, "DirTest");
        private const string SubFolder = "SubFolder";
        private const string TestFile = "TestFile.txt";
        private string _testRootPath;

        [SetUp]
        public void SetUp()
        {
            _testRootPath = Path.Combine(Application.dataPath, TestRoot);
            Directory.CreateDirectory(_testRootPath);
            Directory.CreateDirectory(Path.Combine(_testRootPath, SubFolder));
            File.WriteAllText(Path.Combine(_testRootPath, TestFile), "test");
            UnityEditor.AssetDatabase.Refresh();
        }

        [TearDown]
        public void TearDown()
        {
            if (!Directory.Exists(_testRootPath)) return;
            Directory.Delete(_testRootPath, true);
            File.Delete(_testRootPath + ".meta");
            UnityEditor.AssetDatabase.Refresh();
        }

        [Test]
        public void GetContext_WithValidPath_ReturnsDirectoryContents()
        {
            // Arrange
            var provider = new DirectoryStructureProvider();

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

            // Assert
            Assert.IsInstanceOf<DirectoryStructureProvider.DirectoryContents>(context);
            var contents = (DirectoryStructureProvider.DirectoryContents)context;
            
            Assert.AreEqual(1, contents.directories.Count);
            Assert.AreEqual(SubFolder, contents.directories[0]);
            Assert.AreEqual(1, contents.files.Count);
            Assert.AreEqual(TestFile, contents.files[0]);
        }

        [Test]
        public void GetContext_WithNullQualifier_ReturnsAssetsRootContents()
        {
            // Arrange
            var provider = new DirectoryStructureProvider();

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

            // Assert
            Assert.IsInstanceOf<DirectoryStructureProvider.DirectoryContents>(context);
            var contents = (DirectoryStructureProvider.DirectoryContents)context;

            // Check that the test folder we created is present in the root listing
            Assert.Contains(TestRoot, contents.directories);
        }

        [Test]
        public void GetContext_WithInvalidPath_ReturnsErrorString()
        {
            // Arrange
            var provider = new DirectoryStructureProvider();
            var invalidPath = Path.Combine(TestRoot, "InvalidFolder");

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

            // Assert
            Assert.IsInstanceOf<string>(context);
            Assert.IsTrue(((string)context).StartsWith("Error: Directory does not exist"));
        }
    }
}