"""Google Calendar tools exposed to HomeAgent and Gemini (multi-calendar support).""" from datetime import datetime, time, timedelta, timezone from typing import Optional from extensions.google_calendar.client import GoogleCalendarClient from homeagent.config import get_settings from homeagent.tools.base import tool _calendar_client: Optional[GoogleCalendarClient] = None def get_calendar_client() -> GoogleCalendarClient: global _calendar_client if _calendar_client is None: _calendar_client = GoogleCalendarClient() return _calendar_client def _parse_iso_datetime(dt_str: str) -> datetime: """Parse ISO formatted string into datetime.""" dt_str = dt_str.strip() if dt_str.endswith("Z"): dt_str = dt_str[:-1] + "+00:00" dt = datetime.fromisoformat(dt_str) if dt.tzinfo is None: dt = dt.astimezone() return dt @tool( name="calendar_list_calendars", description="Показать список всех доступных Google Календарей (основной, рабочие, личные, командные).", ) async def calendar_list_calendars() -> str: """Список доступных календарей.""" settings = get_settings() if not settings.GOOGLE_CALENDAR_ENABLED: return "Интеграция с Google Календарем отключена (GOOGLE_CALENDAR_ENABLED=False)." client = get_calendar_client() if not client.is_configured(): return ( "Google Календарь не настроен. Добавьте service_account.json или credentials.json " "согласно инструкциям в docs/SETUP.md" ) try: calendars = await client.list_calendars() if not calendars: return "Не найдено ни одного доступного календаря." lines = [f"Доступные Google Календари ({len(calendars)}):"] for cal in calendars: cal_id = cal.get("id", "") summary = cal.get("summary", "Без названия") primary_tag = " ⭐ (Основной)" if cal.get("primary") else "" lines.append(f"- **{summary}**{primary_tag} [ID: `{cal_id}`]") return "\n".join(lines) except Exception as e: return f"Ошибка получения списка календарей: {type(e).__name__}: {str(e)}" @tool( name="calendar_list_events", description="Получить события и встречи сразу со ВСЕХ доступных Google Календарей (или из конкретного календаря) на указанное количество дней вперед.", ) async def calendar_list_events( days_ahead: int = 7, max_results: int = 25, calendar: Optional[str] = None, ) -> str: """Список событий календаря. Args: days_ahead: На сколько дней вперед искать события (по умолчанию 7) max_results: Максимальное количество событий (по умолчанию 25) calendar: Имя или ID конкретного календаря, если нужно отфильтровать (по умолчанию проверяются ВСЕ календари) """ settings = get_settings() if not settings.GOOGLE_CALENDAR_ENABLED: return "Интеграция с Google Календарем отключена (GOOGLE_CALENDAR_ENABLED=False)." client = get_calendar_client() if not client.is_configured(): return ( "Google Календарь не настроен. Добавьте service_account.json или credentials.json " "в корень проекта согласно инструкциям в docs/SETUP.md" ) try: now = datetime.now().astimezone() future = now + timedelta(days=days_ahead) events = await client.list_events( time_min=now, time_max=future, max_results=max_results, calendar_id=calendar, ) scope_desc = f"календаря '{calendar}'" if calendar else "всех доступных календарей" if not events: return f"В ближайшие {days_ahead} дн. событий из {scope_desc} не найдено." lines = [f"События из {scope_desc} на ближайшие {days_ahead} дн. (найдено: {len(events)}):"] for event in events: event_id = event.get("id", "") summary = event.get("summary", "Без названия") start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date") end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date") cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else "" lines.append(f"- {cal_label}**{summary}**: c {start} по {end} [ID: `{event_id}`]") return "\n".join(lines) except Exception as e: return f"Ошибка получения событий календаря: {type(e).__name__}: {str(e)}" @tool( name="calendar_today_schedule", description="Получить расписание встреч и событий на сегодня (или захватить завтра) сразу со ВСЕХ доступных Google Календарей (личных, рабочих, учебных, командных).", ) async def calendar_today_schedule(calendar: Optional[str] = None, include_tomorrow: bool = False) -> str: """Расписание на сегодняшний день по всем календарям. Args: calendar: Опционально: фильтр по конкретному календарю (название или ID) include_tomorrow: Если True, включить также расписание на завтрашний день """ client = get_calendar_client() if not client.is_configured(): return "Google Календарь не настроен в .env" try: now = datetime.now().astimezone() start_of_day = datetime.combine(now.date(), time.min).replace(tzinfo=now.tzinfo) target_date = now.date() + timedelta(days=1) if include_tomorrow else now.date() end_of_day = datetime.combine(target_date, time.max).replace(tzinfo=now.tzinfo) events = await client.list_events( time_min=start_of_day, time_max=end_of_day, max_results=50, calendar_id=calendar, ) scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям" period_title = f"сегодня ({now.strftime('%d.%m.%Y')})" if not include_tomorrow else f"сегодня и завтра ({now.strftime('%d.%m')} - {target_date.strftime('%d.%m.%Y')})" if not events: return f"На {period_title} по {scope_desc} запланированных встреч нет." lines = [f"📅 Расписание на {period_title} по {scope_desc}:"] for event in events: summary = event.get("summary", "Без названия") start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date") end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date") desc = event.get("description", "") desc_note = f" ({desc[:60]}...)" if desc else "" cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else "" lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}") return "\n".join(lines) except Exception as e: return f"Ошибка получения расписания: {type(e).__name__}: {str(e)}" @tool( name="calendar_tomorrow_schedule", description="Получить расписание встреч и событий на ЗАВТРА сразу со ВСЕХ доступных Google Календарей (личных, рабочих, учебных, командных).", ) async def calendar_tomorrow_schedule(calendar: Optional[str] = None) -> str: """Расписание на завтрашний день по всем календарям. Args: calendar: Опционально: фильтр по конкретному календарю (название или ID) """ client = get_calendar_client() if not client.is_configured(): return "Google Календарь не настроен в .env" try: now = datetime.now().astimezone() tomorrow_date = now.date() + timedelta(days=1) start_of_day = datetime.combine(tomorrow_date, time.min).replace(tzinfo=now.tzinfo) end_of_day = datetime.combine(tomorrow_date, time.max).replace(tzinfo=now.tzinfo) events = await client.list_events( time_min=start_of_day, time_max=end_of_day, max_results=50, calendar_id=calendar, ) scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям" if not events: return f"На завтра ({tomorrow_date.strftime('%d.%m.%Y')}) по {scope_desc} запланированных встреч нет." lines = [f"📅 Расписание на завтра ({tomorrow_date.strftime('%A, %d.%m.%Y')}) по {scope_desc}:"] for event in events: summary = event.get("summary", "Без названия") start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date") end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date") desc = event.get("description", "") desc_note = f" ({desc[:60]}...)" if desc else "" cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else "" lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}") return "\n".join(lines) except Exception as e: return f"Ошибка получения расписания на завтра: {type(e).__name__}: {str(e)}" @tool( name="calendar_date_schedule", description="Получить расписание встреч и событий на любую конкретную дату (формат 'YYYY-MM-DD' или ключевые слова 'сегодня', 'завтра') со всех доступных Google Календарей.", ) async def calendar_date_schedule(date_str: str, calendar: Optional[str] = None) -> str: """Расписание на указанную дату. Args: date_str: Дата в формате 'YYYY-MM-DD' (например '2026-11-08') или слова 'today', 'сегодня', 'tomorrow', 'завтра' calendar: Опционально: фильтр по конкретному календарю """ client = get_calendar_client() if not client.is_configured(): return "Google Календарь не настроен в .env" try: now = datetime.now().astimezone() clean = date_str.strip().lower() if clean in ("today", "сегодня"): target_date = now.date() elif clean in ("tomorrow", "завтра"): target_date = now.date() + timedelta(days=1) elif clean in ("yesterday", "вчера"): target_date = now.date() - timedelta(days=1) else: target_date = datetime.strptime(clean, "%Y-%m-%d").date() start_of_day = datetime.combine(target_date, time.min).replace(tzinfo=now.tzinfo) end_of_day = datetime.combine(target_date, time.max).replace(tzinfo=now.tzinfo) events = await client.list_events( time_min=start_of_day, time_max=end_of_day, max_results=50, calendar_id=calendar, ) scope_desc = f"календарю '{calendar}'" if calendar else "всем календарям" if not events: return f"На дату {target_date.strftime('%d.%m.%Y')} по {scope_desc} запланированных встреч нет." lines = [f"📅 Расписание на {target_date.strftime('%A, %d.%m.%Y')} по {scope_desc}:"] for event in events: summary = event.get("summary", "Без названия") start = event.get("start", {}).get("dateTime") or event.get("start", {}).get("date") end = event.get("end", {}).get("dateTime") or event.get("end", {}).get("date") desc = event.get("description", "") desc_note = f" ({desc[:60]}...)" if desc else "" cal_label = f"[{event.get('_calendar_name', 'Календарь')}] " if not calendar else "" lines.append(f"- {cal_label}**{summary}**: {start} - {end}{desc_note}") return "\n".join(lines) except Exception as e: return f"Ошибка получения расписания на {date_str}: {type(e).__name__}: {str(e)}" @tool( name="calendar_create_event", description="Создать новое событие или встречу в Google Календаре. Можно указать в какой именно календарь добавить (по умолчанию — в основной).", ) async def calendar_create_event( summary: str, start_iso: str, end_iso: str, description: str = "", attendees: Optional[list[str]] = None, calendar: Optional[str] = "primary", ) -> str: """Создать встречу в календаре. Args: summary: Название встречи или события start_iso: Время начала в формате ISO 8601 (например: '2026-11-08T10:00:00+03:00') end_iso: Время окончания в формате ISO 8601 (например: '2026-11-08T11:00:00+03:00') description: Описание или повестка встречи attendees: Список email участников calendar: Название или ID календаря, в который добавить событие (по умолчанию 'primary' — основной) """ client = get_calendar_client() if not client.is_configured(): return "Google Календарь не настроен в .env" try: start_dt = _parse_iso_datetime(start_iso) end_dt = _parse_iso_datetime(end_iso) event = await client.create_event( summary=summary, start_time=start_dt, end_time=end_dt, description=description, attendees=attendees, calendar_id=calendar, ) event_id = event.get("id", "") link = event.get("htmlLink", "") return f"Событие '{summary}' успешно создано в календаре! ID: {event_id}. Ссылка: {link}" except Exception as e: return f"Ошибка создания события: {type(e).__name__}: {str(e)}" @tool( name="calendar_delete_event", description="Удалить событие из Google Календаря по его ID.", ) async def calendar_delete_event(event_id: str, calendar: Optional[str] = None) -> str: """Удалить событие из календаря. Args: event_id: ID события (полученный из calendar_list_events) calendar: Название или ID календаря (если известно) """ client = get_calendar_client() if not client.is_configured(): return "Google Календарь не настроен в .env" try: await client.delete_event(event_id=event_id.strip(), calendar_id=calendar) return f"Событие с ID '{event_id}' успешно удалено." except Exception as e: return f"Ошибка удаления события '{event_id}': {type(e).__name__}: {str(e)}"