import subprocess, json

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

# Get token
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")

# Try searching ALL messages (not just inbox) from a known sender
email = 'liz@hightailhikes.com'
url = (f"https://graph.microsoft.com/v1.0/users/{USER}/messages"
       f"?$filter=from/emailAddress/address eq '{email}'"
       f"&$select=subject,from,body"
       f"&$top=1"
       f"&$orderby=receivedDateTime desc")
print(f"URL: {url[:120]}...")

r2 = subprocess.run(['curl', '-s', '-X', 'GET', url,
    '-H', f'Authorization: Bearer {token}', '-H', 'Content-Type: application/json'],
    capture_output=True, text=True)

print(f"Stdout length: {len(r2.stdout)}")
print(f"Stderr: {r2.stderr[:200] if r2.stderr else 'none'}")

if r2.stdout:
    data = json.loads(r2.stdout)
    if 'value' in data:
        print(f"Results: {len(data['value'])}")
        if data['value']:
            msg = data['value'][0]
            print(f"Subject: {msg.get('subject','')[:80]}")
            body = msg.get('body',{}).get('content','')
            print(f"Body length: {len(body)}")
            # Show last 800 chars of body (signature area)
            if body:
                print(f"Body tail:\n{body[-800:]}")
    elif 'error' in data:
        print(f"Error: {json.dumps(data['error'], indent=2)}")
    else:
        print(f"Unexpected: {r2.stdout[:500]}")
else:
    print("Empty response")
