from __future__ import annotations from typing import Any from yuxi.channels.adapters.imessage.bridge_client import BlueBubblesClient from yuxi.utils.logging_config import logger async def search_contacts(bridge: BlueBubblesClient, query: str, limit: int = 20) -> list[dict[str, Any]]: """搜索联系人。""" try: contacts = await bridge.query_contacts([query]) return contacts[:limit] except Exception as e: logger.warning(f"[iMessage/Directory] Contact search failed: {e}") return [] async def list_recent_chats(bridge: BlueBubblesClient, limit: int = 30) -> list[dict[str, Any]]: """获取最近聊天列表。""" try: chats = await bridge.get_chats() chats.sort(key=lambda c: c.get("lastMessageDate", 0), reverse=True) return chats[:limit] except Exception as e: logger.warning(f"[iMessage/Directory] Failed to list recent chats: {e}") return [] async def search_groups(bridge: BlueBubblesClient, name_query: str, limit: int = 20) -> list[dict[str, Any]]: """搜索群组。""" try: chats = await bridge.get_chats() groups = [c for c in chats if ";-;" in c.get("guid", "") or "@chat" in c.get("guid", "")] if name_query: name_lower = name_query.lower() groups = [ g for g in groups if name_lower in g.get("displayName", "").lower() or name_lower in g.get("guid", "").lower() ] groups.sort(key=lambda c: c.get("lastMessageDate", 0), reverse=True) return groups[:limit] except Exception as e: logger.warning(f"[iMessage/Directory] Group search failed: {e}") return [] async def get_chat_info(bridge: BlueBubblesClient, chat_guid: str) -> dict[str, Any]: """获取聊天详细信息。""" try: messages = await bridge.get_chat_messages(chat_guid, limit=1) chats = await bridge.get_chats() for chat in chats: if chat.get("guid") == chat_guid: return { "guid": chat_guid, "display_name": chat.get("displayName", ""), "participants": chat.get("participants", []), "last_message": messages[0] if messages else None, } return {"guid": chat_guid, "display_name": "", "participants": []} except Exception as e: logger.warning(f"[iMessage/Directory] Failed to get chat info for {chat_guid}: {e}") return {"guid": chat_guid, "display_name": ""}