#!/usr/bin/env python3
"""
Quick IMAP test using Python's imaplib
"""
import imaplib
import os
import sys
from pathlib import Path

# Load .env
env_file = Path(__file__).parent.parent / '.env'
if env_file.exists():
    for line in env_file.read_text().splitlines():
        if line.strip() and not line.startswith('#'):
            key, _, value = line.partition('=')
            os.environ[key.strip()] = value.strip()

def test_imap():
    host = os.environ.get('IMAP_HOST', 'imap.gmail.com')
    port = int(os.environ.get('IMAP_PORT', '993'))
    user = os.environ.get('IMAP_USER')
    password = os.environ.get('IMAP_PASS')
    
    print(f"Connecting to {host}:{port}...", file=sys.stderr)
    
    try:
        # Connect
        mail = imaplib.IMAP4_SSL(host, port)
        print(f"Connected! Server says: {mail.welcome}", file=sys.stderr)
        
        # Login
        mail.login(user, password)
        print(f"Logged in as {user}", file=sys.stderr)
        
        # Select inbox
        status, messages = mail.select('INBOX')
        num_messages = int(messages[0])
        print(f"INBOX has {num_messages} messages", file=sys.stderr)
        
        # Fetch last 5 messages
        if num_messages > 0:
            start = max(1, num_messages - 4)
            typ, data = mail.fetch(f'{start}:{num_messages}', '(FLAGS BODY[HEADER.FIELDS (FROM SUBJECT DATE)])')
            
            for i in range(0, len(data), 2):
                if data[i]:
                    msg = data[i][1].decode('utf-8', errors='ignore')
                    print(msg)
                    print('-' * 80)
        
        mail.close()
        mail.logout()
        print("✅ IMAP test successful!", file=sys.stderr)
        
    except Exception as e:
        print(f"❌ Error: {e}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    test_imap()
