"""QR code generation node for calendar events (vEvent)."""

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 QRCodeEventInput(QRStyleInput):
    summary: str = Field(
        ...,
        description="Event title/summary",
    )
    start: str = Field(
        ...,
        description="Start date/time in ISO 8601 format (e.g. 2025-01-15T10:00:00Z)",
    )
    end: str = Field(
        default="",
        description="End date/time in ISO 8601 format (e.g. 2025-01-15T11:00:00Z)",
    )
    location: str = Field(
        default="",
        description="Event location",
    )
    description: str = Field(
        default="",
        description="Event description",
    )


def _to_vcal_datetime(iso_str: str) -> str:
    """Convert ISO 8601 string to vCalendar format (YYYYMMDDTHHmmSSZ)."""
    cleaned = iso_str.replace("-", "").replace(":", "")
    # Remove any fractional seconds
    if "." in cleaned:
        cleaned = cleaned[: cleaned.index(".")] + cleaned[cleaned.index(".") :].lstrip(".0123456789")
    return cleaned


class QRCodeEventNode(BaseNode):
    input_schema = QRCodeEventInput
    output_schema = QRCodeOutput

    metadata = qr_node_metadata(
        name="Event QR Code",
        description="Generate a QR code that adds a calendar event",
        icon="📅",
    )

    async def execute_logic(
        self,
        validated_inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> QRCodeOutput:
        start = _to_vcal_datetime(validated_inputs["start"])

        lines = [
            "BEGIN:VEVENT",
            f"SUMMARY:{validated_inputs['summary']}",
            f"DTSTART:{start}",
        ]

        if validated_inputs.get("end"):
            lines.append(f"DTEND:{_to_vcal_datetime(validated_inputs['end'])}")
        if validated_inputs.get("location"):
            lines.append(f"LOCATION:{validated_inputs['location']}")
        if validated_inputs.get("description"):
            lines.append(f"DESCRIPTION:{validated_inputs['description']}")

        lines.append("END:VEVENT")

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