using ClaudeDo.Worker.Agents;

namespace ClaudeDo.Worker.Tests.Services;

public sealed class AgentFileServiceTests : IDisposable
{
    private readonly string _agentDir;
    private readonly AgentFileService _service;

    public AgentFileServiceTests()
    {
        _agentDir = Path.Combine(Path.GetTempPath(), $"claudedo_agents_test_{Guid.NewGuid():N}");
        Directory.CreateDirectory(_agentDir);
        _service = new AgentFileService(_agentDir);
    }

    [Fact]
    public async Task Scan_Returns_Empty_For_Empty_Directory()
    {
        var agents = await _service.ScanAsync();
        Assert.Empty(agents);
    }

    [Fact]
    public async Task Scan_Parses_Frontmatter()
    {
        var content = "---\nname: Test Agent\ndescription: A test agent for unit tests\n---\n\nYou are a test agent.";
        await File.WriteAllTextAsync(Path.Combine(_agentDir, "test.md"), content);

        var agents = await _service.ScanAsync();
        Assert.Single(agents);
        Assert.Equal("Test Agent", agents[0].Name);
        Assert.Equal("A test agent for unit tests", agents[0].Description);
        Assert.EndsWith("test.md", agents[0].Path);
    }

    [Fact]
    public async Task Scan_Uses_Filename_When_No_Frontmatter()
    {
        await File.WriteAllTextAsync(Path.Combine(_agentDir, "simple.md"), "Just instructions.");

        var agents = await _service.ScanAsync();
        Assert.Single(agents);
        Assert.Equal("simple", agents[0].Name);
        Assert.Equal("", agents[0].Description);
    }

    [Fact]
    public async Task Write_And_Read_Roundtrips()
    {
        var path = Path.Combine(_agentDir, "new-agent.md");
        var content = "---\nname: New\ndescription: Desc\n---\nBody";
        await _service.WriteAsync(path, content);

        var read = await _service.ReadAsync(path);
        Assert.Equal(content, read);
    }

    [Fact]
    public async Task Delete_Removes_File()
    {
        var path = Path.Combine(_agentDir, "to-delete.md");
        await File.WriteAllTextAsync(path, "temp");

        await _service.DeleteAsync(path);
        Assert.False(File.Exists(path));
    }

    [Fact]
    public async Task Scan_Ignores_Non_Md_Files()
    {
        await File.WriteAllTextAsync(Path.Combine(_agentDir, "notes.txt"), "not an agent");
        await File.WriteAllTextAsync(Path.Combine(_agentDir, "agent.md"), "---\nname: Real\ndescription: Yes\n---\nBody");

        var agents = await _service.ScanAsync();
        Assert.Single(agents);
        Assert.Equal("Real", agents[0].Name);
    }

    public void Dispose()
    {
        try { Directory.Delete(_agentDir, true); } catch { }
    }
}
