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'

# 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 with --url flag and proper encoding
email = 'liz@hightailhikes.com'
# Build URL with proper encoding
params = {
    '$filter': f"from/emailAddress/address eq '{email}'",
    '$select': 'subject,from,body',
    '$top': '1',
    '$orderby': 'receivedDateTime desc'
}
qs = urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
url = f"https://graph.microsoft.com/v1.0/users/{USER}/messages?{qs}"
print(f"URL: {url[:150]}...")

r2 = subprocess.run(['curl', '-s', '--url', 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 length: {len(r2.stderr)}")

if r2.stdout:
    try:
        data = json.loads(r2.stdout)
    except:
        print(f"Raw: {r2.stdout[:500]}")
        raise
    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)}")
            if body:
                print(f"Body tail (last 800 chars):\n{body[-800:]}")
    elif 'error' in data:
        print(f"Error: {json.dumps(data['error'], indent=2)}")
    else:
        print(f"Keys: {list(data.keys())}")
        print(f"Raw: {r2.stdout[:500]}")
else:
    print("Empty response")
    # Try with -G and -d params instead
    print("\nRetrying with -G approach...")
    r3 = subprocess.run(['curl', '-s', '-G',
        f'https://graph.microsoft.com/v1.0/users/{USER}/messages',
        '--data-urlencode', f"$filter=from/emailAddress/address eq '{email}'",
        '--data-urlencode', '$select=subject,from,body',
        '--data-urlencode', '$top=1',
        '--data-urlencode', '$orderby=receivedDateTime desc',
        '-H', f'Authorization: Bearer {token}',
        '-H', 'Content-Type: application/json'],
        capture_output=True, text=True)
    print(f"Stdout length: {len(r3.stdout)}")
    if r3.stdout:
        data = json.loads(r3.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)}")
                if body:
                    print(f"Body tail:\n{body[-800:]}")
        elif 'error' in data:
            print(f"Error: {json.dumps(data['error'], indent=2)}")
