from __future__ import annotations

from aiogram.types import Message

from core.protocol import Attachment, IncomingMessage, OutgoingEvent, OutgoingMessage, OutgoingUI


def from_message(message: Message) -> IncomingMessage | None:
    """Convert aiogram Message to IncomingMessage. Returns None for General topic."""
    thread_id = message.message_thread_id
    if thread_id is None:
        return None
    return IncomingMessage(
        user_id=str(message.from_user.id),
        chat_id=str(thread_id),
        text=message.text or message.caption or "",
        attachments=_extract_attachments(message),
        platform="telegram",
    )


def _extract_attachments(message: Message) -> list[Attachment]:
    attachments: list[Attachment] = []
    if message.photo:
        file = message.photo[-1]
        attachments.append(Attachment(
            type="image",
            url=f"tg://file/{file.file_id}",
            mime_type="image/jpeg",
        ))
    if message.document:
        attachments.append(Attachment(
            type="document",
            url=f"tg://file/{message.document.file_id}",
            mime_type=message.document.mime_type or "application/octet-stream",
            filename=message.document.file_name,
        ))
    if message.voice:
        attachments.append(Attachment(
            type="audio",
            url=f"tg://file/{message.voice.file_id}",
            mime_type="audio/ogg",
        ))
    return attachments


def format_outgoing(event: OutgoingEvent) -> str:
    """Extract text from an outgoing event for sending to Telegram."""
    if isinstance(event, (OutgoingMessage, OutgoingUI)):
        return event.text
    return str(event)
