using System.Text.Json;
using ClawdDotNet.Core.Tools;
using MailKit;
using MailKit.Net.Imap;
using MailKit.Net.Smtp;
using MailKit.Search;
using Microsoft.Extensions.Logging;
using MimeKit;

using ClawdDotNet.Core.State;

namespace ClawdDotNet.Tools.Mail;

public sealed class MailTool : IAgentTool, IToolJobProvider
{
    public string Name => "Mail";

    public string Description => "Erlaubt das Senden und Empfangen von E-Mails über SMTP und IMAP.";

    public JsonElement InputSchema { get; } = JsonDocument.Parse("""
        {
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["send", "read_inbox", "read_message", "mark_read"],
                    "description": "Die auszuführende Aktion"
                },
                "to": {
                    "type": "string",
                    "description": "Empfänger-E-Mail (nur für send)"
                },
                "subject": {
                    "type": "string",
                    "description": "Betreff (nur für send)"
                },
                "body": {
                    "type": "string",
                    "description": "Inhalt der E-Mail (nur für send)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Maximale Anzahl an E-Mails zum Abrufen (nur für read_inbox)"
                },
                "messageId": {
                    "type": "string",
                    "description": "Die ID der Nachricht (für read_message oder mark_read)"
                }
            },
            "required": ["action"]
        }
        """).RootElement.Clone();

    public async Task<ToolResult> ExecuteAsync(
        JsonElement input,
        AgentToolContext context,
        CancellationToken ct)
    {
        var action = input.GetProperty("action").GetString()
            ?? throw new ArgumentException("'action' is required");

        try
        {
            return action switch
            {
                "send" => await HandleSendAsync(input, context, ct),
                "read_inbox" => await HandleReadInboxAsync(input, context, ct),
                "read_message" => await HandleReadMessageAsync(input, context, ct),
                "mark_read" => await HandleMarkReadAsync(input, context, ct),
                _ => ToolResult.Fail($"Unbekannte Aktion: {action}")
            };
        }
        catch (Exception ex)
        {
            context.Logger.LogError(ex, "Fehler bei Mail Aktion {Action}", action);
            return ToolResult.Fail($"Fehler: {ex.Message}");
        }
    }

    private async Task<ToolResult> HandleSendAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
    {
        var to = input.TryGetProperty("to", out var t) ? t.GetString() : null;
        var subject = input.TryGetProperty("subject", out var s) ? s.GetString() : "(Kein Betreff)";
        var body = input.TryGetProperty("body", out var b) ? b.GetString() : "";

        if (string.IsNullOrWhiteSpace(to)) return ToolResult.Fail("'to' ist erforderlich.");

        // Sicherheitsprüfung: Erlaubte Empfänger
        if (!IsRecipientAllowed(to, context))
        {
            return ToolResult.Fail($"Sicherheitsfehler: Senden an '{to}' ist nicht erlaubt.");
        }

        var config = context.ToolConfig;
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("ClawdDotNet", config["username"]?.ToString()));
        message.To.Add(MailboxAddress.Parse(to));
        message.Subject = subject;
        message.Body = new TextPart("plain") { Text = body };

        using var client = new SmtpClient();
        await client.ConnectAsync(config["smtpHost"]?.ToString(), (config["smtpPort"] is JsonElement sp ? sp.GetInt32() : 587), true, ct);
        await client.AuthenticateAsync(config["username"]?.ToString(), config["password"]?.ToString(), ct);
        await client.SendAsync(message, ct);
        await client.DisconnectAsync(true, ct);

        return ToolResult.Ok($"E-Mail erfolgreich an {to} gesendet.");
    }

    private async Task<ToolResult> HandleReadInboxAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
    {
        var limit = input.TryGetProperty("limit", out var l) ? l.GetInt32() : 10;
        var config = context.ToolConfig;

        using var client = new ImapClient();
        await client.ConnectAsync(config["imapHost"]?.ToString(), (config["imapPort"] is JsonElement ip ? ip.GetInt32() : 993), true, ct);
        await client.AuthenticateAsync(config["username"]?.ToString(), config["password"]?.ToString(), ct);

        await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
        var messages = new List<object>();

        for (int i = client.Inbox!.Count - 1; i >= Math.Max(0, client.Inbox!.Count - limit); i--)
        {
            var msg = await client.Inbox!.GetMessageAsync(i, ct);
            messages.Add(new
            {
                Id = i.ToString(),
                Date = msg.Date,
                From = msg.From.ToString(),
                Subject = msg.Subject
            });
        }

        await client.DisconnectAsync(true, ct);
        return ToolResult.Ok(JsonSerializer.Serialize(messages, new JsonSerializerOptions { WriteIndented = true }));
    }

    private async Task<ToolResult> HandleReadMessageAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
    {
        if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
        {
            return ToolResult.Fail("'messageId' (Index) ist erforderlich.");
        }

        var config = context.ToolConfig;
        using var client = new ImapClient();
        await client.ConnectAsync(config["imapHost"]?.ToString(), (config["imapPort"] is JsonElement ip ? ip.GetInt32() : 993), true, ct);
        await client.AuthenticateAsync(config["username"]?.ToString(), config["password"]?.ToString(), ct);

        await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
        var msg = await client.Inbox!.GetMessageAsync(index, ct);
        
        var result = new
        {
            Id = index.ToString(),
            Date = msg.Date,
            From = msg.From.ToString(),
            Subject = msg.Subject,
            Body = msg.TextBody
        };

        await client.DisconnectAsync(true, ct);
        return ToolResult.Ok(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
    }

    private async Task<ToolResult> HandleMarkReadAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
    {
        if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
        {
            return ToolResult.Fail("'messageId' (Index) ist erforderlich.");
        }

        var config = context.ToolConfig;
        using var client = new ImapClient();
        await client.ConnectAsync(config["imapHost"]?.ToString(), (config["imapPort"] is JsonElement ip ? ip.GetInt32() : 993), true, ct);
        await client.AuthenticateAsync(config["username"]?.ToString(), config["password"]?.ToString(), ct);

        await client.Inbox!.OpenAsync(FolderAccess.ReadWrite, ct);
        await client.Inbox!.AddFlagsAsync(index, MessageFlags.Seen, true, ct);
        
        await client.DisconnectAsync(true, ct);
        return ToolResult.Ok($"Nachricht {index} als gelesen markiert.");
    }

    private bool IsRecipientAllowed(string email, AgentToolContext context)
    {
        if (!context.ToolConfig.TryGetValue("allowedRecipients", out var val) || val is not JsonElement je)
        {
            return false;
        }

        var allowed = je.EnumerateArray().Select(x => x.GetString()?.ToLowerInvariant()).ToList();
        return allowed.Contains(email.ToLowerInvariant());
    }

    public IReadOnlyList<ToolJobDefinition> GetJobDefinitions() =>
    [
        new("mail_check_unread", "Mail Check", "Prüft regelmäßig auf neue ungelesene E-Mails")
    ];

    public async Task<ToolJobResult> ExecuteJobAsync(
        string jobTypeId,
        IReadOnlyDictionary<string, object?> toolConfig,
        IStateStore stateStore,
        ILogger logger,
        CancellationToken ct,
        string? agentId = null,
        string? workspacePath = null)
    {
        if (jobTypeId != "mail_check_unread")
            return ToolJobResult.NoAction($"Unbekannter Job: {jobTypeId}");

        try
        {
            using var client = new ImapClient();
            var imapHost = toolConfig.TryGetValue("imapHost", out var h) ? h?.ToString() : null;
            var imapPort = toolConfig.TryGetValue("imapPort", out var p) ? (p is long l ? (int)l : (p is int i ? i : 993)) : 993;
            var username = toolConfig.TryGetValue("username", out var u) ? u?.ToString() : null;
            var password = toolConfig.TryGetValue("password", out var pw) ? pw?.ToString() : null;

            if (string.IsNullOrWhiteSpace(imapHost) || string.IsNullOrWhiteSpace(username))
                return ToolJobResult.NoAction("Mail-Konfiguration unvollständig");

            await client.ConnectAsync(imapHost, imapPort, true, ct);
            await client.AuthenticateAsync(username ?? "", password ?? "", ct);

            await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
            
            // Wir suchen nach ungelesenen Nachrichten
            var uids = await client.Inbox!.SearchAsync(SearchQuery.NotSeen, ct);
            
            if (uids.Count == 0)
            {
                await client.DisconnectAsync(true, ct);
                return ToolJobResult.NoAction("Keine neuen ungelesenen Mails");
            }

            // Um zu vermeiden, dass wir bei jedem Tick für die gleichen Mails wecken,
            // speichern wir die höchste UID, die wir bereits gemeldet haben.
            var lastUidStr = await stateStore.GetAsync("mail_last_notified_uid", ct);
            uint lastUid = uint.TryParse(lastUidStr, out var lu) ? lu : 0;

            var newUids = uids.Where(uid => uid.Id > lastUid).OrderBy(uid => uid.Id).ToList();

            if (newUids.Count == 0)
            {
                await client.DisconnectAsync(true, ct);
                return ToolJobResult.NoAction("Keine neuen Mails seit der letzten Prüfung");
            }

            // Die neuesten Nachrichten abrufen für die Zusammenfassung
            var summary = new List<string>();
            foreach (var uid in newUids.Take(5))
            {
                var msg = await client.Inbox!.GetMessageAsync(uid, ct);
                summary.Add($"- Von: {msg.From}, Betreff: {msg.Subject}");
            }

            if (newUids.Count > 5) summary.Add($"- ... und {newUids.Count - 5} weitere");

            // Höchste UID speichern
            var maxUid = newUids.Max(u => u.Id);
            await stateStore.SetAsync("mail_last_notified_uid", maxUid.ToString(), ct);

            await client.DisconnectAsync(true, ct);

            return ToolJobResult.Wake(
                $"Du hast {newUids.Count} neue ungelesene E-Mails erhalten:\n" + string.Join("\n", summary),
                logSummary: $"{newUids.Count} neue Mails gefunden"
            );
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Fehler im Mail Background Job");
            return ToolJobResult.NoAction($"Fehler: {ex.Message}");
        }
    }
}
