"""Email Trigger node for receiving real-time new email notifications via IMAP IDLE."""

from typing import Any

from flowire_sdk import (
    BaseNode,
    BaseNodeOutput,
    HandleConfig,
    NodeExecutionContext,
    NodeHandles,
    NodeMetadata,
)
from pydantic import BaseModel, Field

from fw_nodes_email.credentials import IMAPCredentialSchema


class EmailTriggerInput(BaseModel):
    """Configuration for email trigger."""

    credential_id: str = Field(
        ...,
        description="IMAP credential with server details and authentication",
    )
    folder: str = Field(
        default="INBOX",
        description="Mailbox folder to monitor (e.g., INBOX)",
    )


class EmailTriggerOutput(BaseNodeOutput):
    """Output from an incoming email event."""

    event_type: str = Field(..., description="Event type (always 'new_email')")
    message_id: str = Field(default="", description="Message-ID header")
    from_address: str = Field(default="", description="Sender address")
    to: str = Field(default="", description="Recipient addresses")
    cc: str = Field(default="", description="CC recipients")
    subject: str = Field(default="", description="Email subject")
    date: str = Field(default="", description="Date sent (ISO 8601)")
    body_plain: str = Field(default="", description="Plain text body")
    body_html: str = Field(default="", description="HTML body")
    attachments: list[dict[str, Any]] = Field(default_factory=list, description="Attachment metadata")
    raw_event: dict = Field(default_factory=dict, description="Full event payload")


class EmailTriggerNode(BaseNode):
    """Trigger workflow when a new email arrives via IMAP IDLE.

    This node uses IMAP IDLE to receive real-time push notifications
    when new emails arrive in the monitored folder. The Connection Manager
    maintains a persistent IMAP connection.

    Unlike polling with Read Emails, this triggers instantly when mail arrives.
    """

    input_schema = EmailTriggerInput
    output_schema = EmailTriggerOutput
    credential_schema = IMAPCredentialSchema

    metadata = NodeMetadata(
        name="Email Trigger",
        description="Trigger when a new email arrives (via IMAP IDLE)",
        category="email",
        icon="📨",
        color="#4A90D9",
        handles=NodeHandles(
            inputs=[],  # No inputs - entry point
            outputs=[HandleConfig(id="default", position="right")],
        ),
        is_entry_point=True,
        is_stream_trigger=True,
        stream_type="imap_idle",
        show_execute_button=True,
    )

    async def execute(
        self,
        inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> EmailTriggerOutput:
        """Transform stream trigger data into structured output.

        When the Connection Manager receives an IMAP IDLE notification,
        it triggers this node with the email data in _trigger_data.
        """
        inputs = await self.parse_expressions_in_schema_fields(inputs, context)

        trigger_data = inputs.get("_trigger_data") or {}
        event_type = trigger_data.get("event_type", "new_email")
        event_data = trigger_data.get("event_data", {})

        return EmailTriggerOutput(
            event_type=event_type,
            message_id=event_data.get("message_id", ""),
            from_address=event_data.get("from", ""),
            to=event_data.get("to", ""),
            cc=event_data.get("cc", ""),
            subject=event_data.get("subject", ""),
            date=event_data.get("date", ""),
            body_plain=event_data.get("body_plain", ""),
            body_html=event_data.get("body_html", ""),
            attachments=event_data.get("attachments", []),
            raw_event=trigger_data,
        )
