using System.ComponentModel;
using System.Text.Json;
using ColaFlow.Modules.Mcp.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;

namespace ColaFlow.Modules.Mcp.Application.SdkResources;

/// <summary>
/// MCP Resource: Sprints (SDK-based implementation)
/// Provides access to Sprint data
/// </summary>
[McpServerResourceType]
public class SprintsSdkResource
{
    private readonly IProjectRepository _projectRepository;
    private readonly ITenantContext _tenantContext;
    private readonly ILogger<SprintsSdkResource> _logger;

    public SprintsSdkResource(
        IProjectRepository projectRepository,
        ITenantContext tenantContext,
        ILogger<SprintsSdkResource> logger)
    {
        _projectRepository = projectRepository ?? throw new ArgumentNullException(nameof(projectRepository));
        _tenantContext = tenantContext ?? throw new ArgumentNullException(nameof(tenantContext));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    [McpServerResource]
    [Description("Get the currently active Sprint(s)")]
    public async Task<string> GetCurrentSprintAsync(CancellationToken cancellationToken = default)
    {
        var tenantId = _tenantContext.GetCurrentTenantId();

        _logger.LogDebug("Fetching active sprints for tenant {TenantId} (SDK)", tenantId);

        // Get active sprints
        var activeSprints = await _projectRepository.GetActiveSprintsAsync(cancellationToken);

        if (activeSprints.Count == 0)
        {
            _logger.LogWarning("No active sprints found for tenant {TenantId}", tenantId);
            throw new McpNotFoundException("No active sprints found");
        }

        // Map to DTOs with statistics
        var sprintDtos = activeSprints.Select(sprint => new
        {
            id = sprint.Id.Value,
            name = sprint.Name,
            goal = sprint.Goal,
            status = sprint.Status.ToString(),
            startDate = sprint.StartDate,
            endDate = sprint.EndDate,
            createdAt = sprint.CreatedAt,
            statistics = new
            {
                totalTasks = sprint.TaskIds?.Count ?? 0
            }
        }).ToList();

        var result = JsonSerializer.Serialize(new
        {
            sprints = sprintDtos,
            total = sprintDtos.Count
        }, new JsonSerializerOptions { WriteIndented = true });

        _logger.LogInformation("Retrieved {Count} active sprints for tenant {TenantId} (SDK)",
            sprintDtos.Count, tenantId);

        return result;
    }
}
