"""QR code generation node for email (mailto:) links."""

from typing import Any
from urllib.parse import quote

from flowire_sdk import BaseNode, NodeExecutionContext
from pydantic import Field

from fw_nodes_qrcode.shared import QRCodeOutput, QRStyleInput, generate_qr_image, qr_node_metadata


class QRCodeEmailInput(QRStyleInput):
    email: str = Field(
        ...,
        description="Recipient email address",
    )
    subject: str = Field(
        default="",
        description="Email subject line",
    )
    body: str = Field(
        default="",
        description="Email body text",
    )
    cc: str = Field(
        default="",
        description="CC recipients (comma-separated)",
    )
    bcc: str = Field(
        default="",
        description="BCC recipients (comma-separated)",
    )


class QRCodeEmailNode(BaseNode):
    input_schema = QRCodeEmailInput
    output_schema = QRCodeOutput

    metadata = qr_node_metadata(
        name="Email QR Code",
        description="Generate a QR code that opens an email compose window",
        icon="📧",
    )

    async def execute_logic(
        self,
        validated_inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> QRCodeOutput:
        params = []
        if validated_inputs.get("subject"):
            params.append(f"subject={quote(validated_inputs['subject'])}")
        if validated_inputs.get("body"):
            params.append(f"body={quote(validated_inputs['body'])}")
        if validated_inputs.get("cc"):
            params.append(f"cc={quote(validated_inputs['cc'])}")
        if validated_inputs.get("bcc"):
            params.append(f"bcc={quote(validated_inputs['bcc'])}")

        mailto = f"mailto:{validated_inputs['email']}"
        if params:
            mailto += "?" + "&".join(params)

        return generate_qr_image(mailto, validated_inputs, context)
