
import json, imaplib, email
from pathlib import Path
STATE=Path('/opt/data/agent-state/email-watch/usha_invictus_seen.json')
creds={}
for line in Path('/opt/data/secrets/.yahoo-credentials').read_text().splitlines():
    if '=' in line:
        k,v=line.split('=',1); creds[k.strip()]=v.strip().strip('"').strip("'")
seen=set(json.loads(STATE.read_text())) if STATE.exists() else set()
m=imaplib.IMAP4_SSL('imap.mail.yahoo.com',993); m.login(creds['YAHOO_EMAIL'], creds['YAHOO_APP_PASSWORD']); m.select('INBOX', readonly=True)
for mid in ['9609','9890','9943','9976']:
    st,md=m.fetch(mid,'(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID FROM SUBJECT DATE)])')
    if st=='OK' and md and isinstance(md[0], tuple):
        msg=email.message_from_bytes(md[0][1])
        message_id=(msg.get('Message-ID') or msg.get('Message-Id') or '').strip()
        print(mid, msg.get('From'), msg.get('Subject'), message_id)
        if message_id:
            seen.add(f"{creds['YAHOO_EMAIL']}|{message_id}")
STATE.parent.mkdir(parents=True, exist_ok=True)
STATE.write_text(json.dumps(sorted(seen)[-1000:], indent=2))
print(f'seen_count={len(seen)}')
m.logout()
