"""
Built-in tool: calendar_lookup

Reads calendar events from Google Calendar for a given date.

Authentication options (in priority order):
  1. GOOGLE_SERVICE_ACCOUNT_KEY env var — JSON key for service account impersonation
  2. Per-tenant OAuth (future: Phase 3 portal) — not yet implemented
  3. Graceful degradation: returns informative message if not configured

This tool is read-only (requires_confirmation=False in registry).
"""

from __future__ import annotations

import json
import logging
import os
from datetime import datetime, timezone

logger = logging.getLogger(__name__)


async def calendar_lookup(
    date: str,
    calendar_id: str = "primary",
    **kwargs: object,
) -> str:
    """
    Look up calendar events for a specific date.

    Args:
        date:        Date in YYYY-MM-DD format.
        calendar_id: Google Calendar ID. Defaults to 'primary'.

    Returns:
        Formatted string listing events for the given date,
        or an informative message if Google Calendar is not configured.
    """
    service_account_key_json = os.getenv("GOOGLE_SERVICE_ACCOUNT_KEY", "")
    if not service_account_key_json:
        return (
            "Calendar lookup is not configured. "
            "Set the GOOGLE_SERVICE_ACCOUNT_KEY environment variable to enable calendar access."
        )

    try:
        import asyncio

        result = await asyncio.get_event_loop().run_in_executor(
            None,
            _fetch_calendar_events_sync,
            service_account_key_json,
            calendar_id,
            date,
        )
        return result
    except Exception:
        logger.exception("Calendar lookup failed for date=%s calendar=%s", date, calendar_id)
        return f"Calendar lookup failed for {date}. Please try again."


def _fetch_calendar_events_sync(
    service_account_key_json: str,
    calendar_id: str,
    date: str,
) -> str:
    """
    Synchronous implementation — runs in thread executor to avoid blocking event loop.

    Uses google-api-python-client with service account credentials.
    """
    try:
        from google.oauth2 import service_account
        from googleapiclient.discovery import build
    except ImportError:
        return (
            "Google Calendar library not installed. "
            "Run: uv add google-api-python-client google-auth"
        )

    try:
        key_data = json.loads(service_account_key_json)
    except json.JSONDecodeError:
        return "Invalid GOOGLE_SERVICE_ACCOUNT_KEY: not valid JSON."

    try:
        credentials = service_account.Credentials.from_service_account_info(
            key_data,
            scopes=["https://www.googleapis.com/auth/calendar.readonly"],
        )
    except Exception as exc:
        return f"Failed to create Google credentials: {exc}"

    # Parse the date and create RFC3339 time boundaries for the day
    try:
        date_obj = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=timezone.utc)
    except ValueError:
        return f"Invalid date format: {date!r}. Expected YYYY-MM-DD."

    time_min = date_obj.strftime("%Y-%m-%dT00:00:00Z")
    time_max = date_obj.strftime("%Y-%m-%dT23:59:59Z")

    try:
        service = build("calendar", "v3", credentials=credentials, cache_discovery=False)
        events_result = (
            service.events()
            .list(
                calendarId=calendar_id,
                timeMin=time_min,
                timeMax=time_max,
                singleEvents=True,
                orderBy="startTime",
            )
            .execute()
        )
    except Exception as exc:
        logger.warning("Google Calendar API error: %s", exc)
        return f"Calendar API error: {exc}"

    items = events_result.get("items", [])
    if not items:
        return f"No events found on {date}."

    lines = [f"Calendar events for {date}:\n"]
    for event in items:
        start = event["start"].get("dateTime", event["start"].get("date", "Unknown time"))
        summary = event.get("summary", "Untitled event")
        lines.append(f"- {start}: {summary}")

    return "\n".join(lines)
