from __future__ import annotations from typing import TYPE_CHECKING, Any from yuxi.utils.logging_config import logger if TYPE_CHECKING: from nio import AsyncClient async def search_users( client: AsyncClient, query: str, limit: int = 20, ) -> list[dict[str, Any]]: try: resp = await client.search_user_directory(query, limit=limit) results = getattr(resp, "results", []) return [ { "user_id": r.user_id, "display_name": getattr(r, "display_name", ""), "avatar_url": getattr(r, "avatar_url", ""), } for r in results ] except Exception as e: logger.debug(f"Matrix user directory search failed: {e}") return [] async def search_groups( client: AsyncClient, query: str, server: str | None = None, ) -> list[dict[str, Any]]: try: full_query = query if server else query resp = await client.room_directory_search(full_query, server=server) results = getattr(resp, "results", []) return [ { "room_id": getattr(r, "room_id", ""), "name": getattr(r, "name", ""), "alias": getattr(r, "canonical_alias", ""), "topic": getattr(r, "topic", ""), "num_joined_members": getattr(r, "num_joined_members", 0), "world_readable": getattr(r, "world_readable", False), "guest_can_join": getattr(r, "guest_can_join", False), } for r in results ] except Exception as e: logger.debug(f"Matrix group directory search failed: {e}") return [] async def resolve_room_alias( client: AsyncClient, alias: str, ) -> dict[str, Any] | None: try: resp = await client.room_resolve_alias(alias) return { "room_id": resp.room_id if hasattr(resp, "room_id") else "", "servers": getattr(resp, "servers", []), } except Exception as e: logger.debug(f"Matrix room alias resolution failed for {alias}: {e}") return None async def list_public_rooms( client: AsyncClient, server: str | None = None, limit: int = 50, since: str | None = None, ) -> list[dict[str, Any]]: try: resp = await client.public_rooms( server=server, limit=limit, since=since, ) chunks = getattr(resp, "chunk", []) return [ { "room_id": getattr(r, "room_id", ""), "name": getattr(r, "name", ""), "alias": getattr(r, "canonical_alias", ""), "topic": getattr(r, "topic", ""), "num_joined_members": getattr(r, "num_joined_members", 0), "world_readable": getattr(r, "world_readable", False), } for r in chunks ] except Exception as e: logger.debug(f"Matrix public rooms listing failed: {e}") return []