#!/usr/bin/env python3
"""Microsoft Graph API email for chad@cfrfl.com"""
import requests
import json
import sys

CONFIG = {
    "tenant_id": "aa37e64c-10f3-456d-b991-f5c47b5ce08e",
    "client_id": "072a499a-d477-4d0a-a020-345bc7b8eee8",
    "client_secret": "KCs8Q~iXags1O6RfxUCO~82l~2VWhF~wMHuL_apg",
    "user_email": "chad@cfrfl.com"
}

def get_token():
    url = f"https://login.microsoftonline.com/{CONFIG['tenant_id']}/oauth2/v2.0/token"
    data = {"client_id": CONFIG["client_id"], "client_secret": CONFIG["client_secret"],
            "scope": "https://graph.microsoft.com/.default", "grant_type": "client_credentials"}
    resp = requests.post(url, data=data)
    return resp.json()["access_token"] if resp.status_code == 200 else None

def list_emails(unread_only=False, count=10):
    token = get_token()
    headers = {"Authorization": f"Bearer {token}"}
    f = "&$filter=isRead eq false" if unread_only else ""
    url = f"https://graph.microsoft.com/v1.0/users/{CONFIG['user_email']}/messages?$top={count}&$select=id,subject,from,receivedDateTime,isRead,bodyPreview{f}&$orderby=receivedDateTime desc"
    return requests.get(url, headers=headers).json().get("value", [])

def read_email(msg_id):
    token = get_token()
    url = f"https://graph.microsoft.com/v1.0/users/{CONFIG['user_email']}/messages/{msg_id}"
    return requests.get(url, headers={"Authorization": f"Bearer {token}"}).json()

def send_email(to, subject, body, cc=None):
    token = get_token()
    msg = {"message": {"subject": subject, "body": {"contentType": "Text", "content": body},
           "toRecipients": [{"emailAddress": {"address": to}}]}}
    if cc: msg["message"]["ccRecipients"] = [{"emailAddress": {"address": cc}}]
    url = f"https://graph.microsoft.com/v1.0/users/{CONFIG['user_email']}/sendMail"
    return requests.post(url, headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, json=msg).status_code == 202

def reply_email(msg_id, body):
    token = get_token()
    url = f"https://graph.microsoft.com/v1.0/users/{CONFIG['user_email']}/messages/{msg_id}/reply"
    return requests.post(url, headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, 
                        json={"message": {"body": {"contentType": "Text", "content": body}}}).status_code == 202

if __name__ == "__main__":
    if len(sys.argv) < 2: print("Usage: o365_email.py [list|read|send|reply]"); sys.exit(1)
    if sys.argv[1] == "list":
        for e in list_emails("--unread" in sys.argv, 10):
            print(f"{'📬' if not e.get('isRead') else '📖'} {e['receivedDateTime'][:16]} | {e.get('from',{}).get('emailAddress',{}).get('address','?')}")
            print(f"   Subject: {e.get('subject','')}\n   Preview: {e.get('bodyPreview','')[:80]}...\n")
