using System.Text.Json;
using ColaFlow.Modules.Mcp.Application.DTOs;
using ColaFlow.Modules.Mcp.Application.Services;
using ColaFlow.Modules.Mcp.Application.Tools.Validation;
using ColaFlow.Modules.Mcp.Contracts.Tools;
using ColaFlow.Modules.Mcp.Domain.Exceptions;
using ColaFlow.Modules.Mcp.Domain.Services;
using ColaFlow.Modules.IssueManagement.Domain.Enums;
using ColaFlow.Modules.IssueManagement.Domain.Repositories;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.Tools;

/// <summary>
/// MCP Tool: update_status
/// Updates the status of an existing Issue
/// Generates a Diff Preview and creates a PendingChange for approval
/// </summary>
public class UpdateStatusTool(
    IPendingChangeService pendingChangeService,
    IIssueRepository issueRepository,
    DiffPreviewService diffPreviewService,
    ILogger<UpdateStatusTool> logger)
    : IMcpTool
{
    private readonly IPendingChangeService _pendingChangeService = pendingChangeService ?? throw new ArgumentNullException(nameof(pendingChangeService));
    private readonly IIssueRepository _issueRepository = issueRepository ?? throw new ArgumentNullException(nameof(issueRepository));
    private readonly DiffPreviewService _diffPreviewService = diffPreviewService ?? throw new ArgumentNullException(nameof(diffPreviewService));
    private readonly ILogger<UpdateStatusTool> _logger = logger ?? throw new ArgumentNullException(nameof(logger));

    public string Name => "update_status";

    public string Description => "Update the status of an existing issue. " +
                                  "Supports workflow transitions (Backlog → Todo → InProgress → Done). " +
                                  "Requires human approval before being applied.";

    public McpToolInputSchema InputSchema => new()
    {
        Type = "object",
        Properties = new Dictionary<string, JsonSchemaProperty>
        {
            ["issueId"] = new()
            {
                Type = "string",
                Format = "uuid",
                Description = "The ID of the issue to update"
            },
            ["newStatus"] = new()
            {
                Type = "string",
                Enum = new[] { "Backlog", "Todo", "InProgress", "Done" },
                Description = "The new status to set"
            }
        },
        Required = new List<string> { "issueId", "newStatus" }
    };

    public async Task<McpToolResult> ExecuteAsync(
        McpToolCall toolCall,
        CancellationToken cancellationToken)
    {
        try
        {
            _logger.LogInformation("Executing update_status tool");

            // 1. Parse and validate input
            var issueId = ToolParameterParser.ParseGuid(toolCall.Arguments, "issueId", required: true)!.Value;
            var newStatus = ToolParameterParser.ParseEnum<IssueStatus>(toolCall.Arguments, "newStatus", required: true)!.Value;

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

            var oldStatus = issue.Status;

            // 3. Build before and after data for diff preview
            var beforeData = new
            {
                id = issue.Id,
                title = issue.Title,
                type = issue.Type.ToString(),
                status = oldStatus.ToString(),
                priority = issue.Priority.ToString()
            };

            var afterData = new
            {
                id = issue.Id,
                title = issue.Title,
                type = issue.Type.ToString(),
                status = newStatus.ToString(), // Only status changed
                priority = issue.Priority.ToString()
            };

            // 4. Generate Diff Preview (UPDATE operation)
            var diff = _diffPreviewService.GenerateUpdateDiff(
                entityType: "Issue",
                entityId: issueId,
                beforeEntity: beforeData,
                afterEntity: afterData,
                entityKey: $"{issue.Type}-{issue.Id.ToString().Substring(0, 8)}" // Simplified key
            );

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

            _logger.LogInformation(
                "PendingChange created: {PendingChangeId} - UPDATE Issue {IssueId} status: {OldStatus} → {NewStatus}",
                pendingChange.Id, issueId, oldStatus, newStatus);

            // 6. Return pendingChangeId to AI
            return new McpToolResult
            {
                Content = new[]
                {
                    new McpToolContent
                    {
                        Type = "text",
                        Text = $"Issue status update request submitted for approval.\n\n" +
                               $"**Pending Change ID**: {pendingChange.Id}\n" +
                               $"**Status**: Pending Approval\n" +
                               $"**Issue**: {issue.Title}\n" +
                               $"**Old Status**: {oldStatus}\n" +
                               $"**New Status**: {newStatus}\n\n" +
                               $"A human user must approve this change before the issue status is updated. " +
                               $"The change will expire at {pendingChange.ExpiresAt:yyyy-MM-dd HH:mm} UTC if not approved."
                    }
                },
                IsError = false
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error executing update_status tool");

            return new McpToolResult
            {
                Content = new[]
                {
                    new McpToolContent
                    {
                        Type = "text",
                        Text = $"Error: {ex.Message}"
                    }
                },
                IsError = true
            };
        }
    }
}
