"""QR code generation node for contact information (vCard)."""

from typing import Any

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 QRCodeContactInput(QRStyleInput):
    first_name: str = Field(
        ...,
        description="First name",
    )
    last_name: str = Field(
        default="",
        description="Last name",
    )
    phone: str = Field(
        default="",
        description="Phone number",
    )
    email: str = Field(
        default="",
        description="Email address",
    )
    organization: str = Field(
        default="",
        description="Company or organization name",
    )
    title: str = Field(
        default="",
        description="Job title",
    )
    url: str = Field(
        default="",
        description="Website URL",
    )
    address: str = Field(
        default="",
        description="Street address",
    )
    note: str = Field(
        default="",
        description="Additional notes",
    )


class QRCodeContactNode(BaseNode):
    input_schema = QRCodeContactInput
    output_schema = QRCodeOutput

    metadata = qr_node_metadata(
        name="Contact QR Code",
        description="Generate a QR code with contact information (vCard)",
        icon="👤",
    )

    async def execute_logic(
        self,
        validated_inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> QRCodeOutput:
        first = validated_inputs["first_name"]
        last = validated_inputs.get("last_name", "")
        full_name = f"{first} {last}".strip()

        lines = [
            "BEGIN:VCARD",
            "VERSION:3.0",
            f"N:{last};{first}",
            f"FN:{full_name}",
        ]

        if validated_inputs.get("phone"):
            lines.append(f"TEL:{validated_inputs['phone']}")
        if validated_inputs.get("email"):
            lines.append(f"EMAIL:{validated_inputs['email']}")
        if validated_inputs.get("organization"):
            lines.append(f"ORG:{validated_inputs['organization']}")
        if validated_inputs.get("title"):
            lines.append(f"TITLE:{validated_inputs['title']}")
        if validated_inputs.get("url"):
            lines.append(f"URL:{validated_inputs['url']}")
        if validated_inputs.get("address"):
            lines.append(f"ADR:;;{validated_inputs['address']};;;;")
        if validated_inputs.get("note"):
            lines.append(f"NOTE:{validated_inputs['note']}")

        lines.append("END:VCARD")

        return generate_qr_image("\n".join(lines), validated_inputs, context)
