#!/usr/bin/env python3
import base64, json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

CREDS_DIR = Path.home() / ".config" / "google-workspace-mcp" / "profiles" / "emerson-north"
HTML_FILE = Path(__file__).parent / "metowi_audit_v2.html"

token_data  = json.loads((CREDS_DIR / "tokens.json").read_text())
creds_json  = json.loads((CREDS_DIR / "credentials.json").read_text())
cc = creds_json.get("installed", creds_json.get("web", {}))
creds = Credentials(
    token=token_data.get("access_token"),
    refresh_token=token_data.get("refresh_token"),
    token_uri=cc.get("token_uri"),
    client_id=cc.get("client_id"),
    client_secret=cc.get("client_secret"),
)
if not creds.valid and creds.expired and creds.refresh_token:
    creds.refresh(Request())
    token_data["access_token"] = creds.token
    (CREDS_DIR / "tokens.json").write_text(json.dumps(token_data, indent=2))

svc = build("gmail", "v1", credentials=creds)

msg = MIMEMultipart("alternative")
msg["Subject"] = "Social Media Audit — April 2026"
msg["From"]    = "bfolsom@emersonnorth.com"
msg["To"]      = ""
msg.attach(MIMEText("Social media audit for @bleutiquehair, @metowi, and @metowiverse. See HTML version.", "plain"))
msg.attach(MIMEText(HTML_FILE.read_text(), "html"))

draft = svc.users().drafts().create(userId="me", body={"message": {"raw": base64.urlsafe_b64encode(msg.as_bytes()).decode()}}).execute()
print(f"Draft ID: {draft['id']}")
