namespace Nexus.Api.Services;

public sealed class TeamService(IAgentService agentService) : ITeamService
{
    public async Task<IReadOnlyList<TeamMember>> GetTeamAsync(CancellationToken ct = default)
    {
        var agents = await agentService.GetAgentsAsync(ct);
        var team = new List<TeamMember>(agents.Count);

        foreach (var agent in agents)
        {
            var identity = await ReadIdentityAsync(agent.Workspace, ct);
            team.Add(new TeamMember(
                agent.Id, agent.Name, agent.Role, agent.Model,
                agent.Status, agent.LastSeen, agent.Workspace, agent.Description,
                identity));
        }

        return team;
    }

    private static async Task<string> ReadIdentityAsync(string? workspace, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(workspace) || !Directory.Exists(workspace))
            return string.Empty;

        var identityFile = Path.Combine(workspace, "IDENTITY.md");
        if (!File.Exists(identityFile))
            return string.Empty;

        var content = await File.ReadAllTextAsync(identityFile, ct);
        return string.Join("\n", content.Split('\n').Where(l => l.StartsWith("- **")).Take(8));
    }
}
