#!/usr/bin/env python3
import json, datetime
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

BASE = "/Users/joemac/.openclaw/workspace/config/gmail"

with open(f"{BASE}/token.json") as f:
    token_data = json.load(f)
with open(f"{BASE}/credentials.json") as f:
    creds_data = json.load(f)

client_config = creds_data.get("installed", creds_data.get("web", {}))

creds = Credentials(
    token=token_data.get("token"),
    refresh_token=token_data.get("refresh_token"),
    token_uri=client_config.get("token_uri", "https://oauth2.googleapis.com/token"),
    client_id=client_config["client_id"],
    client_secret=client_config["client_secret"],
    scopes=token_data.get("scopes", ["https://www.googleapis.com/auth/gmail.readonly"])
)

if creds.expired or not creds.valid:
    creds.refresh(Request())

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

# Last check
with open(f"{BASE}/rob_last_check.json") as f:
    lc = json.load(f)
last_epoch = lc.get("lastCheckEpoch", 0)

query = f"after:{last_epoch}"
results = service.users().messages().list(userId="me", q=query, maxResults=10).execute()
messages = results.get("messages", [])
print(f"Found {len(messages)} messages since last check")

joe_emails = []
other_emails = []

for msg in messages:
    full = service.users().messages().get(
        userId="me", id=msg["id"], format="full",
        metadataHeaders=["From", "Subject", "Date"]
    ).execute()
    headers = {h["name"]: h["value"] for h in full["payload"]["headers"]}
    frm = headers.get("From", "")
    subj = headers.get("Subject", "")
    date = headers.get("Date", "")
    snippet = full.get("snippet", "")

    # Try to get body
    body = ""
    payload = full.get("payload", {})
    if payload.get("body", {}).get("data"):
        import base64
        body = base64.urlsafe_b64decode(payload["body"]["data"]).decode("utf-8", errors="replace")
    elif payload.get("parts"):
        for part in payload["parts"]:
            if part.get("mimeType") == "text/plain" and part.get("body", {}).get("data"):
                import base64
                body = base64.urlsafe_b64decode(part["body"]["data"]).decode("utf-8", errors="replace")
                break

    entry = {
        "from": frm,
        "subject": subj,
        "date": date,
        "snippet": snippet,
        "body": body[:2000]
    }

    if "jlynch@tlcnj.com" in frm.lower() or "josephfl12@gmail.com" in frm.lower():
        joe_emails.append(entry)
    else:
        other_emails.append(entry)

print(json.dumps({"joe_emails": joe_emails, "other_emails": other_emails}, indent=2))

# Update last check
now = datetime.datetime.now(datetime.timezone.utc)
with open(f"{BASE}/rob_last_check.json", "w") as f:
    json.dump({"lastCheck": now.isoformat(), "lastCheckEpoch": int(now.timestamp())}, f)
