"""
Message Logging Helper
=======================
Shared function for logging messages to dp_messages table.

All messages (customer, LIA, manager) are logged using this helper.

Columns used:
- conversation_id: UUID of the conversation
- message_body: The actual message text
- sender: 'lia' | 'customer' | 'manager'
- direction: 'inbound' | 'outbound'
- channel: 'whatsapp' | 'sms' | etc.
- template_key: Template used (nullable)
- mode: 'campaign' | 'intro' | 'nudge' | 'tier_reply' | 'appointment' (nullable)
- ab_variant: A/B test variant (nullable)
- created_at: Timestamp (defaults to now())
"""

from uuid import UUID
from app.db import get_conn


async def log_message(
    conversation_id: str,
    message_body: str,
    sender: str,
    direction: str,
    channel: str,
    template_key: str | None = None,
    mode: str | None = None,
    ab_variant: str | None = None,
) -> bool:
    """
    Log a message to dp_messages table.
    
    Args:
        conversation_id: UUID string of the conversation
        message_body: The message text
        sender: 'lia' | 'customer' | 'manager'
        direction: 'inbound' | 'outbound'
        channel: 'whatsapp' | 'sms' | etc.
        template_key: Template key used (optional)
        mode: Message mode (optional)
        ab_variant: A/B test variant (optional)
    
    Returns:
        True if successful, False otherwise
    """
    conv_uuid = UUID(conversation_id)
    
    conn = await get_conn()
    try:
        await conn.execute(
            """
            INSERT INTO dp_messages (
                conversation_id, message_body, sender, direction,
                channel, template_key, mode, ab_variant
            )
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
            """,
            conv_uuid,
            message_body,
            sender,
            direction,
            channel,
            template_key,
            mode,
            ab_variant,
        )
        return True
    except Exception as e:
        print(f"Error logging message: {e}")
        return False
    finally:
        await conn.close()


async def log_customer_message(
    conversation_id: str,
    message_body: str,
    channel: str = "whatsapp",
    template_key: str | None = None,
    mode: str | None = None,
) -> bool:
    """
    Convenience function to log a customer (inbound) message.
    """
    return await log_message(
        conversation_id=conversation_id,
        message_body=message_body,
        sender="customer",
        direction="inbound",
        channel=channel,
        template_key=template_key,
        mode=mode,
    )


async def log_lia_message(
    conversation_id: str,
    message_body: str,
    channel: str = "whatsapp",
    template_key: str | None = None,
    mode: str | None = None,
    ab_variant: str | None = None,
) -> bool:
    """
    Convenience function to log a LIA (outbound) message.
    """
    return await log_message(
        conversation_id=conversation_id,
        message_body=message_body,
        sender="lia",
        direction="outbound",
        channel=channel,
        template_key=template_key,
        mode=mode,
        ab_variant=ab_variant,
    )


async def log_manager_message(
    conversation_id: str,
    message_body: str,
    channel: str = "whatsapp",
    template_key: str | None = None,
    mode: str | None = None,
) -> bool:
    """
    Convenience function to log a manager (outbound) message.
    """
    return await log_message(
        conversation_id=conversation_id,
        message_body=message_body,
        sender="manager",
        direction="outbound",
        channel=channel,
        template_key=template_key,
        mode=mode,
    )
