"""QR code generation node for WiFi network credentials."""

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


def _escape_wifi_field(value: str) -> str:
    """Escape special characters in WiFi QR code fields."""
    for char in ("\\", ";", ",", '"', ":"):
        value = value.replace(char, f"\\{char}")
    return value


class QRCodeWiFiInput(QRStyleInput):
    ssid: str = Field(
        ...,
        description="WiFi network name (SSID)",
    )
    password: str = Field(
        default="",
        description="WiFi password (leave empty for open networks)",
    )
    security: str = Field(
        default="WPA",
        description="Security type",
        json_schema_extra={"enum": ["WPA", "WEP", "nopass"]},
    )
    hidden: bool = Field(
        default=False,
        description="Whether the network is hidden",
    )


class QRCodeWiFiNode(BaseNode):
    input_schema = QRCodeWiFiInput
    output_schema = QRCodeOutput

    metadata = qr_node_metadata(
        name="WiFi QR Code",
        description="Generate a QR code that connects to a WiFi network",
        icon="📶",
    )

    async def execute_logic(
        self,
        validated_inputs: dict[str, Any],
        context: NodeExecutionContext,
    ) -> QRCodeOutput:
        security = validated_inputs["security"]
        ssid = _escape_wifi_field(validated_inputs["ssid"])
        password = _escape_wifi_field(validated_inputs.get("password", ""))
        hidden = "true" if validated_inputs.get("hidden") else "false"

        data = f"WIFI:T:{security};S:{ssid};"
        if security != "nopass" and password:
            data += f"P:{password};"
        data += f"H:{hidden};;"

        return generate_qr_image(data, validated_inputs, context)
