using System.ComponentModel;
using ColaFlow.Modules.Mcp.Application.DTOs;
using ColaFlow.Modules.Mcp.Application.Services;
using ColaFlow.Modules.Mcp.Domain.Exceptions;
using ColaFlow.Modules.Mcp.Domain.Services;
using ColaFlow.Modules.IssueManagement.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;

namespace ColaFlow.Modules.Mcp.Application.SdkTools;

/// <summary>
/// MCP Tool: add_comment (SDK-based implementation)
/// Adds a comment to an existing Issue
/// Generates a Diff Preview and creates a PendingChange for approval
/// </summary>
[McpServerToolType]
public class AddCommentSdkTool
{
    private readonly IPendingChangeService _pendingChangeService;
    private readonly IIssueRepository _issueRepository;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly DiffPreviewService _diffPreviewService;
    private readonly ILogger<AddCommentSdkTool> _logger;

    public AddCommentSdkTool(
        IPendingChangeService pendingChangeService,
        IIssueRepository issueRepository,
        IHttpContextAccessor httpContextAccessor,
        DiffPreviewService diffPreviewService,
        ILogger<AddCommentSdkTool> logger)
    {
        _pendingChangeService = pendingChangeService ?? throw new ArgumentNullException(nameof(pendingChangeService));
        _issueRepository = issueRepository ?? throw new ArgumentNullException(nameof(issueRepository));
        _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
        _diffPreviewService = diffPreviewService ?? throw new ArgumentNullException(nameof(diffPreviewService));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    [McpServerTool]
    [Description("Add a comment to an existing issue. Supports markdown formatting. Requires human approval before being added.")]
    public async Task<string> AddCommentAsync(
        [Description("The ID of the issue to comment on")] Guid issueId,
        [Description("The comment content (supports markdown, max 2000 characters)")] string content,
        CancellationToken cancellationToken = default)
    {
        try
        {
            _logger.LogInformation("Executing add_comment tool (SDK)");

            // 1. Validate content
            if (string.IsNullOrWhiteSpace(content))
                throw new McpInvalidParamsException("Comment content cannot be empty");

            if (content.Length > 2000)
                throw new McpInvalidParamsException("Comment content cannot exceed 2000 characters");

            // 2. Verify issue exists
            var issue = await _issueRepository.GetByIdAsync(issueId, cancellationToken);
            if (issue == null)
                throw new McpNotFoundException("Issue", issueId.ToString());

            // 3. Get API Key ID (to track who created the comment)
            var apiKeyId = _httpContextAccessor.HttpContext?.Items["ApiKeyId"] as Guid?;

            // 4. Build comment data for diff preview
            var commentData = new
            {
                issueId = issueId,
                content = content,
                authorType = "AI",
                authorId = apiKeyId,
                createdAt = DateTime.UtcNow
            };

            // 5. Generate Diff Preview (CREATE Comment operation)
            var diff = _diffPreviewService.GenerateCreateDiff(
                entityType: "Comment",
                afterEntity: commentData,
                entityKey: $"Comment on {issue.Type}-{issue.Id.ToString().Substring(0, 8)}"
            );

            // 6. Create PendingChange
            var pendingChange = await _pendingChangeService.CreateAsync(
                new CreatePendingChangeRequest
                {
                    ToolName = "add_comment",
                    Diff = diff,
                    ExpirationHours = 24
                },
                cancellationToken);

            _logger.LogInformation(
                "PendingChange created: {PendingChangeId} - CREATE Comment on Issue {IssueId}",
                pendingChange.Id, issueId);

            // 7. Return pendingChangeId to AI
            return $"Comment creation request submitted for approval.\n\n" +
                   $"**Pending Change ID**: {pendingChange.Id}\n" +
                   $"**Status**: Pending Approval\n" +
                   $"**Issue**: {issue.Title}\n" +
                   $"**Comment Preview**: {(content.Length > 100 ? content.Substring(0, 100) + "..." : content)}\n\n" +
                   $"A human user must approve this change before the comment is added. " +
                   $"The change will expire at {pendingChange.ExpiresAt:yyyy-MM-dd HH:mm} UTC if not approved.";
        }
        catch (McpException)
        {
            throw; // Re-throw MCP exceptions as-is
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error executing add_comment tool (SDK)");
            throw new McpInvalidParamsException($"Error adding comment: {ex.Message}");
        }
    }
}
