#!/usr/bin/env python3
"""
Batch label Gmail messages using the Gmail API
Usage: python3 gmail-label-batch.py <msg_ids_file> <labels...>
Where msg_ids_file contains one message ID per line
"""

import sys, json, os
from pathlib import Path

def get_service():
    try:
        from google.oauth2.credentials import Credentials
        from google.auth.transport.requests import Request
        from google_auth_oauthlib.flow import InstalledAppFlow
        from googleapiclient.discovery import build
    except ImportError:
        import subprocess
        venv_pip = Path.home() / ".openclaw/workspace/scripts/youtube-playlists/venv/bin/pip"
        if venv_pip.exists():
            subprocess.run([str(venv_pip), "install", "-q",
                           "google-auth", "google-auth-oauthlib", "google-api-python-client"],
                          capture_output=True)
        from google.oauth2.credentials import Credentials
        from google.auth.transport.requests import Request
        from google_auth_oauthlib.flow import InstalledAppFlow
        from googleapiclient.discovery import build

    SCOPES = ["https://www.googleapis.com/auth/gmail.modify"]
    CREDS_PATH = Path.home() / ".config/gmail/credentials.json"
    TOKEN_PATH = Path.home() / ".config/gmail/token.json"

    creds = None
    if TOKEN_PATH.exists():
        creds = Credentials.from_authorized_user_file(str(TOKEN_PATH), SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
            TOKEN_PATH.write_text(creds.to_json())
    
    return build("gmail", "v1", credentials=creds)

def get_label_id(service, label_name):
    """Get label ID by name, creating if necessary"""
    labels = service.users().labels().list(userId="me").execute().get("labels", [])
    for label in labels:
        if label["name"] == label_name:
            return label["id"]
    
    # Create label if not found
    label_body = {
        "name": label_name,
        "labelListVisibility": "labelShow",
        "messageListVisibility": "show"
    }
    result = service.users().labels().create(userId="me", body=label_body).execute()
    return result["id"]

def label_messages(service, msg_ids, label_names):
    """Apply multiple labels to messages"""
    label_ids = [get_label_id(service, name) for name in label_names]
    
    for msg_id in msg_ids:
        try:
            service.users().messages().modify(
                userId="me", id=msg_id,
                body={"addLabelIds": label_ids}
            ).execute()
            print(f"✓ {msg_id}: {', '.join(label_names)}")
        except Exception as e:
            print(f"✗ {msg_id}: {e}")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python3 gmail-label-batch.py <msg_ids_file> <label1> [label2] ...")
        print("  msg_ids_file: file with one message ID per line")
        sys.exit(1)
    
    ids_file = sys.argv[1]
    labels = sys.argv[2:]
    
    if not os.path.exists(ids_file):
        print(f"Error: {ids_file} not found")
        sys.exit(1)
    
    with open(ids_file) as f:
        msg_ids = [line.strip() for line in f if line.strip()]
    
    print(f"Labeling {len(msg_ids)} messages with {labels}")
    svc = get_service()
    label_messages(svc, msg_ids, labels)
    print(f"Done!")

# TONY-APPROVED: 2026-03-01 | sha:1e0cf8b8
