import asyncio
import httpx
import re

MAILPIT_API = "http://sf_mailpit:8025/api/v1/messages"
SANDBOX_EMAIL = "sandbox_1774064971@test.com"

async def test():
    async with httpx.AsyncClient() as client:
        resp = await client.get(MAILPIT_API)
        data = resp.json()
        print(f"Total messages: {data.get('total', 0)}")
        print(f"Count: {data.get('count', 0)}")
        
        messages = data.get('messages', [])
        for i, msg in enumerate(messages):
            print(f"\nMessage {i}:")
            print(f"  Subject: {msg.get('Subject')}")
            print(f"  To: {msg.get('To')}")
            print(f"  From: {msg.get('From')}")
            
            # Check if email is to SANDBOX_EMAIL
            to_list = msg.get("To", [])
            email_found = False
            for recipient in to_list:
                if isinstance(recipient, dict) and recipient.get("Address") == SANDBOX_EMAIL:
                    email_found = True
                    break
                elif isinstance(recipient, str) and recipient == SANDBOX_EMAIL:
                    email_found = True
                    break
            
            if email_found:
                print(f"  ✓ Email is to {SANDBOX_EMAIL}")
                msg_id = msg.get("ID")
                if msg_id:
                    detail_resp = await client.get(f"{MAILPIT_API}/{msg_id}")
                    detail = detail_resp.json()
                    text = detail.get("Text", "")
                    html = detail.get("HTML", "")
                    
                    print(f"  Text length: {len(text)}")
                    print(f"  HTML length: {len(html)}")
                    
                    # Look for token
                    patterns = [
                        r"token=([a-zA-Z0-9\-_]+)",
                        r"/verify/([a-zA-Z0-9\-_]+)",
                        r"verification code: ([a-zA-Z0-9\-_]+)",
                        r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
                    ]
                    
                    for pattern in patterns:
                        if text:
                            matches = re.findall(pattern, text, re.I)
                            if matches:
                                token = matches[0] if isinstance(matches[0], str) else matches[0][0]
                                print(f"  ✓ Found token with pattern '{pattern}': {token}")
                                return token
                    
                    print(f"  ✗ No token found in text")
                    print(f"  Text preview: {text[:200]}...")
                else:
                    print(f"  ✗ No message ID")
            else:
                print(f"  ✗ Email is not to {SANDBOX_EMAIL}")
    
    return None

if __name__ == "__main__":
    token = asyncio.run(test())
    print(f"\nFinal token: {token}")
