#!/usr/bin/env python3
"""
Quick list of AI newsletters in inbox
"""
import sys
import subprocess
from pathlib import Path

WORKSPACE = Path(__file__).parent.parent.parent
EMAIL_SKILL = WORKSPACE / "skills" / "imap-smtp-email"

AI_KEYWORDS = [
    'ai', 'artificial intelligence', 'machine learning', 'ml', 'llm',
    'gpt', 'claude', 'openai', 'anthropic', 'deepmind', 'neural',
    'chatgpt', 'transformer', 'diffusion', 'generative', 'newsletter'
]

def is_ai_newsletter(from_addr, subject):
    text = f"{from_addr} {subject}".lower()
    return any(keyword in text for keyword in AI_KEYWORDS)

def main():
    # Fetch unread emails
    cmd = [
        "python3",
        str(EMAIL_SKILL / "scripts" / "imap-py.py"),
        "search",
        "--unseen",
        "--limit", "50"
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode != 0:
        print("Error fetching emails", file=sys.stderr)
        sys.exit(1)
    
    # Parse output
    emails = []
    lines = result.stdout.strip().split('\n')
    
    current_email = {}
    for line in lines:
        line = line.strip()
        
        if 'UID:' in line:
            if current_email:
                emails.append(current_email)
            uid = line.split('UID:')[1].strip().split()[0]
            current_email = {'uid': uid}
        elif line.startswith('From:'):
            current_email['from'] = line.replace('From:', '').strip()
        elif line.startswith('Subject:'):
            current_email['subject'] = line.replace('Subject:', '').strip()
    
    if current_email:
        emails.append(current_email)
    
    # Filter AI newsletters
    ai_newsletters = [e for e in emails if is_ai_newsletter(e.get('from', ''), e.get('subject', ''))]
    
    print(f"Found {len(ai_newsletters)} AI newsletters out of {len(emails)} unread emails:\n")
    
    for n in ai_newsletters:
        print(f"UID: {n['uid']}")
        print(f"From: {n.get('from', 'Unknown')}")
        print(f"Subject: {n.get('subject', 'No subject')}")
        print()

if __name__ == '__main__':
    main()
