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 ColaFlow.Modules.ProjectManagement.Domain.ValueObjects;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Resources;

/// <summary>
/// Resource: colaflow://projects.get/{id}
/// Gets detailed information about a specific project
/// </summary>
public class ProjectsGetResource(
    IProjectRepository projectRepository,
    ITenantContext tenantContext,
    ILogger<ProjectsGetResource> logger)
    : IMcpResource
{
    public string Uri => "colaflow://projects.get/{id}";
    public string Name => "Project Details";
    public string Description => "Get detailed information about a project";
    public string MimeType => "application/json";
    public string Category => "Projects";
    public string Version => "1.0";

    public McpResourceDescriptor GetDescriptor()
    {
        return new McpResourceDescriptor
        {
            Uri = Uri,
            Name = Name,
            Description = Description,
            MimeType = MimeType,
            Category = Category,
            Version = Version,
            Parameters = new Dictionary<string, string>
            {
                { "id", "Project ID (GUID)" }
            },
            Examples = new List<string>
            {
                "GET colaflow://projects.get/123e4567-e89b-12d3-a456-426614174000",
                "Returns: { id, name, key, description, status, epics: [...] }"
            },
            Tags = new List<string> { "projects", "details", "read-only" },
            IsEnabled = true
        };
    }

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

        // Extract {id} from URI parameters
        if (!request.UriParams.TryGetValue("id", out var idString))
        {
            throw new McpInvalidParamsException("Missing required parameter: id");
        }

        if (!Guid.TryParse(idString, out var projectIdGuid))
        {
            throw new McpInvalidParamsException($"Invalid project ID format: {idString}");
        }

        var projectId = ProjectId.From(projectIdGuid);

        logger.LogDebug("Fetching project {ProjectId} for tenant {TenantId}", projectId, tenantId);

        // Get project with full hierarchy (read-only)
        var project = await projectRepository.GetProjectWithFullHierarchyReadOnlyAsync(projectId, cancellationToken);

        if (project == null)
        {
            throw new McpNotFoundException($"Project not found: {projectId}");
        }

        // Map to DTO
        var projectDto = new
        {
            id = project.Id.Value,
            name = project.Name,
            key = project.Key.ToString(),
            description = project.Description,
            status = project.Status.ToString(),
            ownerId = project.OwnerId.Value,
            createdAt = project.CreatedAt,
            updatedAt = project.UpdatedAt,
            epics = project.Epics?.Select(e => new
            {
                id = e.Id.Value,
                name = e.Name,
                description = e.Description,
                status = e.Status.ToString(),
                priority = e.Priority.ToString(),
                createdAt = e.CreatedAt,
                storyCount = e.Stories?.Count ?? 0
            }).ToList()
        };

        var json = JsonSerializer.Serialize(projectDto, new JsonSerializerOptions { WriteIndented = true });

        logger.LogInformation("Retrieved project {ProjectId} for tenant {TenantId}", projectId, tenantId);

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