import subprocess, json, urllib.parse

TENANT = 'dd4a82e8-85a3-44ac-8800-07945ab4d95f'
CLIENT_ID = 'fabb3421-8b34-484b-bc17-e46de9703418'
CLIENT_SECRET = '~QJ8Q~NyQSs4OcGqHZyPrA2CVnq9KBfKiimntbMO'
USER = 'barbara@bardach.net'

r = subprocess.run(['curl', '-s', '-X', 'POST',
    f'https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token',
    '-d', f'client_id={CLIENT_ID}', '-d', f'client_secret={CLIENT_SECRET}',
    '-d', 'scope=https://graph.microsoft.com/.default', '-d', 'grant_type=client_credentials'],
    capture_output=True, text=True)
token = json.loads(r.stdout)['access_token']
print("Got token")

email = 'kellyy@cpa-cm.com'

# Approach: use $search with from: keyword
# $search requires ConsistencyLevel: eventual header
r2 = subprocess.run(['curl', '-s', '-G',
    f'https://graph.microsoft.com/v1.0/users/{USER}/messages',
    '--data-urlencode', f'$search="from:{email}"',
    '--data-urlencode', '$select=subject,from,body',
    '--data-urlencode', '$top=3',
    '-H', f'Authorization: Bearer {token}',
    '-H', 'Content-Type: application/json',
    '-H', 'ConsistencyLevel: eventual'],
    capture_output=True, text=True)

print(f"Stdout length: {len(r2.stdout)}")
if r2.stdout:
    data = json.loads(r2.stdout)
    if 'value' in data:
        print(f"Results: {len(data['value'])}")
        for i, msg in enumerate(data['value'][:3]):
            subj = msg.get('subject','')[:60]
            frm = msg.get('from',{}).get('emailAddress',{}).get('address','')
            body = msg.get('body',{}).get('content','')
            print(f"\n--- Message {i+1}: {subj} from {frm} ---")
            print(f"Body length: {len(body)}")
            if body:
                # Show last 600 chars
                print(f"Body tail:\n{body[-600:]}")
    elif 'error' in data:
        print(f"Error: {json.dumps(data['error'], indent=2)}")
    else:
        print(f"Raw: {r2.stdout[:500]}")
