using Moq;
using QuantEngine.Application.Services;
using QuantEngine.Core.Interfaces;

namespace QuantEngine.Core.Tests;

public class LearningDatasetServiceTests
{
    [Fact]
    public async Task ExportJsonAsync_TrimsPathAndClampsLimit()
    {
        var reader = new Mock<ILearningDatasetReader>(MockBehavior.Strict);
        reader.Setup(r => r.ReadTrainingExamplesAsync(10000)).ReturnsAsync([]);

        var service = new LearningDatasetService(reader.Object);
        var root = FindRepoRoot();
        var outPath = Path.Combine(root, "Temp", "learning_dataset_test.json");

        if (File.Exists(outPath))
        {
            File.Delete(outPath);
        }

        var result = await service.ExportJsonAsync($"  {outPath}  ", 50000);

        Assert.Equal(Path.GetFullPath(outPath), result);
        Assert.True(File.Exists(result));
        var text = await File.ReadAllTextAsync(result);
        Assert.Contains("\"gate\": \"DATA_MISSING\"", text);
        reader.VerifyAll();
    }

    [Fact]
    public async Task ExportJsonAsync_RejectsBlankPath()
    {
        var service = new LearningDatasetService(new Mock<ILearningDatasetReader>().Object);
        await Assert.ThrowsAsync<ArgumentException>(() => service.ExportJsonAsync(" ", 10));
    }

    private static string FindRepoRoot()
    {
        var current = new DirectoryInfo(AppContext.BaseDirectory);
        while (current != null)
        {
            if (Directory.Exists(Path.Combine(current.FullName, ".git")))
            {
                return current.FullName;
            }
            current = current.Parent;
        }

        throw new InvalidOperationException("Repository root not found.");
    }
}
