using System.Text.Json;
using ColaFlow.Modules.Mcp.Contracts.Resources;
using ColaFlow.Modules.Mcp.Domain.Exceptions;
using ColaFlow.Modules.ProjectManagement.Application.Common.Interfaces;
using ColaFlow.Modules.ProjectManagement.Domain.Repositories;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Resources;

/// <summary>
/// Resource: colaflow://sprints.current
/// Gets the currently active Sprint(s)
/// </summary>
public class SprintsCurrentResource(
    IProjectRepository projectRepository,
    ITenantContext tenantContext,
    ILogger<SprintsCurrentResource> logger)
    : IMcpResource
{
    public string Uri => "colaflow://sprints.current";
    public string Name => "Current Sprint";
    public string Description => "Get the currently active Sprint(s)";
    public string MimeType => "application/json";
    public string Category => "Sprints";
    public string Version => "1.0";

    public async Task<McpResourceContent> GetContentAsync(
        McpResourceRequest request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantContext.GetCurrentTenantId();

        logger.LogDebug("Fetching active sprints for tenant {TenantId}", 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
                // Note: To get completed/in-progress counts, we'd need to query tasks
                // For now, just return total count
            }
        }).ToList();

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

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

        return new McpResourceContent
        {
            Uri = Uri,
            MimeType = MimeType,
            Text = json
        };
    }
}
