from asgiref.sync import sync_to_async
from django.utils import timezone


def messages_to_string(messages: list, author_rewrites: dict | None = None):
    """
    Converts message objects to a formatted string, showing custom_author if set.
    """
    author_rewrites = {
        str(key).strip().upper(): str(value)
        for key, value in (author_rewrites or {}).items()
    }

    def _author_label(message):
        author = (
            message.custom_author
            if message.custom_author
            else message.session.identifier.person.name
        )
        mapped = author_rewrites.get(str(author).strip().upper())
        return mapped if mapped else author

    message_texts = [
        f"[{msg.ts}] <{_author_label(msg)}> {msg.text}" for msg in messages
    ]
    return "\n".join(message_texts)


async def update_last_interaction(session):
    now = timezone.now()
    session.identifier.person.last_interaction = now
    session.last_interaction = now
    await sync_to_async(session.identifier.person.save)()
    await sync_to_async(session.save)()
