#!/usr/bin/env python3
"""Check Tony's Proton inbox for new messages from Dustin or forwarded items."""
import imaplib, email, json, os
from email.header import decode_header
from datetime import datetime, timezone
from pathlib import Path

STATE_FILE = Path.home() / ".openclaw/workspace/memory/proton-inbox-state.json"
SMTP_CONFIG = json.loads(open(Path.home() / ".smtp_config").read())

def decode_str(val):
    if not val:
        return ""
    parts = decode_header(val)
    result = ""
    for part, enc in parts:
        if isinstance(part, bytes):
            result += part.decode(enc or "utf-8", errors="replace")
        else:
            result += part
    return result

def get_body(msg):
    if msg.is_multipart():
        for part in msg.walk():
            if part.get_content_type() == "text/plain":
                try:
                    return part.get_payload(decode=True).decode("utf-8", errors="replace")
                except: pass
    try:
        return msg.get_payload(decode=True).decode("utf-8", errors="replace")
    except:
        return ""

# Load state
state = json.loads(STATE_FILE.read_text()) if STATE_FILE.exists() else {"last_seen_id": 0}
last_seen = state.get("last_seen_id", 0)

mail = imaplib.IMAP4("127.0.0.1", 1143)
mail.starttls()
mail.login(SMTP_CONFIG["user"], SMTP_CONFIG["password"])
mail.select("INBOX")

_, data = mail.search(None, "ALL")
ids = [int(i) for i in data[0].split()]

new_msgs = []
for num in ids:
    if num <= last_seen:
        continue
    _, msg_data = mail.fetch(str(num).encode(), "(RFC822)")
    msg = email.message_from_bytes(msg_data[0][1])
    frm = msg.get("From", "")
    subj = decode_str(msg.get("Subject", ""))
    date = msg.get("Date", "")
    body = get_body(msg)[:500]
    new_msgs.append({"id": num, "from": frm, "subject": subj, "date": date, "body": body})

mail.logout()

if new_msgs:
    print(f"NEW MAIL ({len(new_msgs)} message(s)):")
    for m in new_msgs:
        print(f"\n[{m['id']}] {m['date']}\nFrom: {m['from']}\nSubject: {m['subject']}\nBody: {m['body'][:300]}")
    # Update state
    state["last_seen_id"] = max(m["id"] for m in new_msgs)
    STATE_FILE.write_text(json.dumps(state))
else:
    print("NO_NEW_MAIL")

# TONY-APPROVED: 2026-03-01 | sha:569b051d
