import logging
import os
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent.parent))  # run from repo root

from azure.communication.messages.aio import NotificationMessagesClient
from dotenv import load_dotenv

from whatsapp import Bot
from whatsapp.bindings.azure import AzureBindingClient
from whatsapp.messages import TextMessage
from whatsapp.messages.dialogs import Dialog, DialogContext, DialogTurnResult, DialogTurnStatus

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

load_dotenv()


@Dialog.set(name="GreetingDialog", main=True)
class GreetingDialog(Dialog):
    """A simple greeting dialog that asks for the user's name."""

    @Dialog.step()
    @Dialog.store("user_name")
    async def ask_name(self, dc: DialogContext):
        """Ask the user for their name."""
        message = TextMessage(ctx=dc.ctx, message="Hello! 👋 What's your name?")
        await dc.message.send(message)
        return DialogTurnResult(DialogTurnStatus.Waiting)

    @Dialog.step()
    async def greet_user(self, dc: DialogContext):
        """Greet the user by name."""
        name = dc.get_value("user_name")
        message = TextMessage(ctx=dc.ctx, message=f"Nice to meet you, {name}! 😊")
        await dc.message.send(message)
        return DialogTurnResult(DialogTurnStatus.Complete)


# Create Bot instance
bot = Bot(port=6969)  # used for my local cloudflared tunnel, don't mind the funny number

# Load Dialog into Bot Registry
bot.load_dialog(GreetingDialog)

# Initialize Azure client
endpoint = os.getenv("AZURE_COMMUNICATION_ENDPOINT")
notification_client = NotificationMessagesClient.from_connection_string(endpoint)

# Create Azure binding
azure_binding = AzureBindingClient(
    ctx=bot,
    client=notification_client,
    route="/api/whatsapp/events",
)

# Pass Bot to Binding and Run
bot.run(azure_binding)
