"""
Test 2: Receive and Analyze Email

Demonstrates receiving emails and analyzing them for credentials/auth.
"""

import os
import sys
sys.path.insert(0, ".")

from agent_email import AgentEmailTool

os.environ["AGENTMAIL_API_KEY"] = "your-api-key-here"


def test_receive_and_analyze():
    """Test receiving and analyzing emails"""
    
    tool = AgentEmailTool(agent_id="sofiia-test")
    
    # Get unread emails
    print("Checking for unread emails...")
    emails = tool.receive(unread_only=True, limit=10)
    
    print(f"Found {len(emails)} unread emails\n")
    
    for email in emails:
        print(f"From: {email.get('from')}")
        print(f"Subject: {email.get('subject')}")
        print(f"Date: {email.get('date')}")
        
        # Analyze email
        analysis = tool.analyze_and_extract(email)
        
        print("\n--- Analysis ---")
        print(f"Summary: {analysis['summary']}")
        
        if analysis['action_items']:
            print(f"Action Items: {analysis['action_items']}")
        
        if analysis['credentials']:
            print(f"Credentials Found:")
            for cred in analysis['credentials']:
                print(f"  - {cred['type']}: {cred['redacted']}")
        
        if analysis['auth_urls']:
            print(f"Auth URLs: {analysis['auth_urls']}")
        
        if analysis['files']:
            print(f"Files: {analysis['files']}")
        
        print(f"Sentiment: {analysis['sentiment']}")
        print("\n" + "="*50 + "\n")
    
    return emails


# Test with sample email data
def test_analysis_only():
    """Test analysis without actual API calls"""
    
    tool = AgentEmailTool(agent_id="sofiia-test")
    
    # Sample OTP email
    sample_email = {
        "id": "test-123",
        "from": "service@example.com",
        "to": ["sofiia@agentmail.to"],
        "subject": "Your verification code",
        "body": """Your verification code is: 123456

This code will expire in 5 minutes.

If you didn't request this, please ignore.""",
        "html": """<p>Your verification code is: <strong>123456</strong></p>""",
        "date": "2026-02-23T10:00:00Z"
    }
    
    analysis = tool.analyze_and_extract(sample_email)
    
    print("=== OTP Email Analysis ===")
    print(f"Summary: {analysis['summary']}")
    print(f"Credentials: {analysis['credentials']}")
    print(f"Auth URLs: {analysis['auth_urls']}")
    print(f"Sentiment: {analysis['sentiment']}")
    
    # Sample magic link email
    sample_email2 = {
        "id": "test-456",
        "from": "github@github.com",
        "to": ["sofiia@agentmail.to"],
        "subject": "Sign in to GitHub",
        "body": """Click the link below to sign in to GitHub:

https://github.com/session/abc123def

If you didn't request this, you can ignore this email.""",
        "date": "2026-02-23T09:00:00Z"
    }
    
    analysis2 = tool.analyze_and_extract(sample_email2)
    
    print("\n=== Magic Link Email Analysis ===")
    print(f"Summary: {analysis2['summary']}")
    print(f"Auth URLs: {analysis2['auth_urls']}")


if __name__ == "__main__":
    # Run analysis test first
    test_analysis_only()
    
    # Then try receiving real emails
    # test_receive_and_analyze()
