# Google Calendar Integration Setup

This guide explains how to set up Google Calendar integration for nanobot.

## Features

- **List upcoming events** from your Google Calendar
- **Create calendar events** programmatically
- **Check availability** for time slots
- **Automatic scheduling from emails** - when an email mentions a meeting, nanobot can automatically schedule it

## Prerequisites

1. Google account with Calendar access
2. Google Cloud Project with Calendar API enabled
3. OAuth2 credentials (Desktop app type)

## Setup Steps

### 1. Enable Google Calendar API

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select an existing one
3. Enable the **Google Calendar API**:
   - Navigate to "APIs & Services" > "Library"
   - Search for "Google Calendar API"
   - Click "Enable"

### 2. Configure OAuth Consent Screen

**IMPORTANT:** This step is required before creating credentials.

1. Go to "APIs & Services" > "OAuth consent screen"
2. Choose **"External"** user type (unless you have a Google Workspace account)
3. Fill in required fields:
   - **App name**: "nanobot" (or any name)
   - **User support email**: Your email address
   - **Developer contact information**: Your email address
4. Click "Save and Continue"
5. **Add Scopes:**
   - Click "Add or Remove Scopes"
   - Search for and add: `https://www.googleapis.com/auth/calendar`
   - Click "Update" then "Save and Continue"
6. **Add Test Users (CRITICAL):**
   - Click "Add Users"
   - Add your email address (`adayear2025@gmail.com`)
   - Click "Add" then "Save and Continue"
7. Review and go back to dashboard

### 3. Create OAuth2 Credentials

1. Go to "APIs & Services" > "Credentials"
2. Click "Create Credentials" > "OAuth client ID"
3. Select:
   - **Application type**: **Desktop app**
   - **Name**: "nanobot" (or any name)
4. Click "Create"
5. **Download the credentials JSON file** - click "Download JSON"
6. Save it as `credentials.json` and copy to your server at `~/.nanobot/credentials.json`

### 3. Configure nanobot

Set environment variables or add to your `.env` file:

```bash
# Enable calendar functionality
export NANOBOT_TOOLS__CALENDAR__ENABLED=true

# Path to OAuth2 credentials JSON file
export NANOBOT_TOOLS__CALENDAR__CREDENTIALS_FILE=/path/to/credentials.json

# Optional: Custom token storage location (default: ~/.nanobot/calendar_token.json)
export NANOBOT_TOOLS__CALENDAR__TOKEN_FILE=~/.nanobot/calendar_token.json

# Optional: Calendar ID (default: "primary")
export NANOBOT_TOOLS__CALENDAR__CALENDAR_ID=primary

# Optional: Auto-schedule meetings from emails (default: true)
export NANOBOT_TOOLS__CALENDAR__AUTO_SCHEDULE_FROM_EMAIL=true
```

### 4. First-Time Authorization

**You don't need to manually get or copy any token** - the OAuth flow handles everything automatically.

On first run, when nanobot tries to use the calendar tool, it will:

1. **Automatically open a browser window** for Google OAuth authorization
2. **You sign in** to your Google account in the browser
3. **Grant calendar access** by clicking "Allow"
4. **Automatically save the token** to `~/.nanobot/calendar_token.json` for future use

**Important:** 
- The token is **automatically generated and saved** - you don't need to copy it from anywhere
- This happens **automatically** the first time you use a calendar command
- After the first authorization, you won't need to do this again (the token is reused)
- The token file is created automatically at `~/.nanobot/calendar_token.json`

**Example first run:**
```bash
# First time using calendar - triggers OAuth flow
python3 -m nanobot.cli.commands agent -m "What's on my calendar?"

# Browser opens automatically → Sign in → Grant access → Token saved
# Future runs use the saved token automatically
```

**Note for remote/headless servers:**
If you're running nanobot on a remote server without a display, you have two options:

1. **Run OAuth on your local machine first:**
   - Run nanobot locally once to complete OAuth
   - Copy the generated `~/.nanobot/calendar_token.json` to your remote server
   - The token will work on the remote server

2. **Use SSH port forwarding:**
   - The OAuth flow uses a local web server
   - You may need to set up port forwarding or use a different OAuth flow method

## Usage Examples

### List Upcoming Events

```
User: "What's on my calendar?"
Agent: [Uses calendar tool to list events]
```

### Create an Event

```
User: "Schedule a meeting tomorrow at 2pm"
Agent: [Creates calendar event]
```

### Automatic Email Scheduling

When an email mentions a meeting:

```
Email: "Hi, let's have a meeting tomorrow at 2pm in Conference Room A"
Agent: [Automatically extracts meeting info and creates calendar event]
Agent: "I've scheduled a meeting for tomorrow at 2pm in Conference Room A"
```

## Calendar Tool API

The calendar tool supports three actions:

### 1. List Events

```python
calendar(
    action="list_events",
    max_results=10,  # Optional, default: 10
    time_min="2024-01-15T00:00:00Z"  # Optional, defaults to now
)
```

### 2. Create Event

```python
calendar(
    action="create_event",
    title="Team Meeting",
    start_time="tomorrow 2pm",  # or "2024-01-15T14:00:00"
    end_time="tomorrow 3pm",     # Optional, defaults to 1 hour after start
    description="Discuss project progress",  # Optional
    location="Conference Room A",           # Optional
    attendees=["colleague@example.com"]      # Optional list
)
```

**Time formats:**
- Relative: `"tomorrow 2pm"`, `"in 1 hour"`, `"in 2 days"`
- ISO format: `"2024-01-15T14:00:00"`

### 3. Check Availability

```python
calendar(
    action="check_availability",
    start_time="2024-01-15T14:00:00",
    end_time="2024-01-15T15:00:00"
)
```

## Troubleshooting

### "Error: Could not authenticate with Google Calendar"

- Ensure `credentials_file` path is correct
- Check that the credentials JSON file is valid
- Run nanobot once to complete OAuth flow

### "Error accessing Google Calendar API"

- Verify Calendar API is enabled in Google Cloud Console
- Check that OAuth consent screen is configured
- Ensure your email is added as a test user (if app is in testing mode)

### Token Expired

The tool automatically refreshes expired tokens. If refresh fails:
1. Delete `~/.nanobot/calendar_token.json`
2. Run nanobot again to re-authorize

## Security Notes

- Keep your `credentials.json` file secure (don't commit to git)
- The `calendar_token.json` file contains sensitive access tokens
- Use file permissions: `chmod 600 ~/.nanobot/calendar_token.json`
- Consider using environment variables or a secrets manager for production

## Integration with Email Channel

When `auto_schedule_from_email` is enabled, nanobot will:

1. Monitor incoming emails
2. Detect meeting-related keywords (meeting, appointment, call, etc.)
3. Extract meeting details (time, location, attendees)
4. Automatically create calendar events
5. Confirm with the user

This works best when:
- Emails contain clear time references ("tomorrow at 2pm", "next Monday")
- Meeting details are in the email body or subject
- The agent has access to the email channel

