# /// script
# dependencies = [
#   "requests",
# ]
# ///

import requests
import os
import imaplib
import email
from email.header import decode_header

user = os.environ.get("MAIL_USER")
password = os.environ.get("MAIL_PASS")

N = 15

def send_ntfy():
    print("Checking for new email ... ")
    if not password:
        print("Please set your password in the MAIL_PASS environment variable")
        return

    if not user:
        print("Please set your user in the MAIL_USER environment variable")
        return

    conn = imaplib.IMAP4_SSL("box.unbl.ink")
    conn.login(user, password)

    status, messages = conn.select("INBOX")
    status, unread = conn.search(None, "UnSeen")


    try:
        unread = unread[0].decode()
    except IndexError:
        print("No new messages found")
    unread_list = unread.split(" ")
    if unread_list == ['']:
        print("No new messages found")
        return

    print(f"Found {len(unread_list)} unread emails")
    if unread_list:
        for msg_num in unread_list:
            # fetch the email message by ID
            res, msg = conn.fetch(msg_num, "(RFC822)")
            for response in msg:
                if isinstance(response, tuple):
                    msg = email.message_from_bytes(response[1])
                    subject, encoding = decode_header(msg["Subject"])[0]
                    if isinstance(subject, bytes):
                        subject = subject.decode(encoding)
                    From, encoding = decode_header(msg.get("From"))[0]
                    if isinstance(From, bytes):
                        From = From.decode(encoding)
                    print(f"Found {subject}")
                    requests.post(
                        "https://ntfy.unbl.ink/207-comms",
                        data=subject.encode("utf-8"),
                        headers={
                            "Title": From,
                            "Tags": "envelope",
                            "Click": "https://box.unbl.ink/mail/?_task=mail&_mbox=INBOX"
                        }
                    )
    conn.close()
    conn.logout()

if __name__ == "__main__":
    send_ntfy()

