#!/usr/bin/env python3
"""Create Gmail draft with EN-branded Metowi social audit email."""

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_social_audit.html"

def get_gmail():
    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"),
        scopes=token_data.get("scope", "").split(),
    )
    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))
    return build("gmail", "v1", credentials=creds)

html_body = HTML_FILE.read_text()

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 TikTok. See HTML version.",
    "plain"
))
msg.attach(MIMEText(html_body, "html"))

raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()

svc = get_gmail()
draft = svc.users().drafts().create(
    userId="me",
    body={"message": {"raw": raw}},
).execute()

print(f"Draft created: {draft['id']}")
print(f"Message ID:    {draft['message']['id']}")
