# core/handlers/chat.py
from __future__ import annotations

from core.protocol import IncomingCommand, OutgoingMessage


def _command(platform: str, name: str) -> str:
    prefix = "!" if platform == "matrix" else "/"
    return f"{prefix}{name}"


async def handle_new_chat(event: IncomingCommand, auth_mgr, platform, chat_mgr, settings_mgr) -> list:
    if not await auth_mgr.is_authenticated(event.user_id):
        return [
            OutgoingMessage(
                chat_id=event.chat_id,
                text=f"Введите {_command(event.platform, 'start')} чтобы начать.",
            )
        ]
    name = " ".join(event.args) if event.args else None
    ctx = await chat_mgr.get_or_create(
        user_id=event.user_id,
        chat_id=event.chat_id,
        platform=event.platform,
        surface_ref=event.chat_id,
        name=name,
    )
    return [OutgoingMessage(chat_id=event.chat_id, text=f"Создан чат: {ctx.display_name}")]


async def handle_rename(event: IncomingCommand, auth_mgr, platform, chat_mgr, settings_mgr) -> list:
    if not event.args:
        return [
            OutgoingMessage(
                chat_id=event.chat_id,
                text=f"Укажите название: {_command(event.platform, 'rename')} Название",
            )
        ]
    ctx = await chat_mgr.rename(event.chat_id, " ".join(event.args))
    return [OutgoingMessage(chat_id=event.chat_id, text=f"Переименован в: {ctx.display_name}")]


async def handle_archive(event: IncomingCommand, auth_mgr, platform, chat_mgr, settings_mgr) -> list:
    await chat_mgr.archive(event.chat_id)
    return [OutgoingMessage(chat_id=event.chat_id, text="Чат архивирован.")]


async def handle_list_chats(event: IncomingCommand, auth_mgr, platform, chat_mgr, settings_mgr) -> list:
    chats = await chat_mgr.list_active(event.user_id)
    if not chats:
        return [OutgoingMessage(chat_id=event.chat_id, text="Нет активных чатов.")]
    lines = [f"• {c.display_name} ({c.chat_id})" for c in chats]
    return [OutgoingMessage(chat_id=event.chat_id, text="\n".join(lines))]
