#!/usr/bin/env python3
# Copyright 2026 Stephen William Wiley
# This software comes with absolutely no warranty or implied warranty.
# You may modify and redistribute it provided this notice remains intact.
# By using this software you agree to the terms of this license.

import re
import os as _os
import fcntl as _fcntl
import hashlib as _hashlib
import mailbox as _mailbox
from contextlib import contextmanager as _contextmanager
from email import policy as _policy
from email.parser import BytesParser as _BytesParser
from email.message import EmailMessage as _EmailMessage
from email.utils import formatdate as _formatdate, make_msgid as _make_msgid

import agent as _agent


def readmail():
    """Read and clear the current agent inbox. Record any messages to keep."""
    text = _read_mailbox()
    return {"text": (text or "No mail.") +
            "\n\nRecord any messages you want to keep."}


def _system_context():
    incoming = _read_mailbox()
    return "Current agent mailbox (now truncated):\n" + incoming if incoming else ""


def mail(to: str, subject: str, body: str):
    """Send mail to an existing agent name, or to user."""
    return {"text": _send_mail(to, subject, body)}


@_contextmanager
def _locked_mailbox(path, mode, *, nonblocking=False):
    # Never follow a mailbox symlink. Keep delivery and truncation on one inode.
    with open(path, mode, opener=lambda path, flags: _os.open(path, flags | _os.O_NOFOLLOW)) as source:
        scope = getattr(_agent.execution, "cancellation", None)
        if nonblocking:
            _fcntl.flock(source, _fcntl.LOCK_EX | _fcntl.LOCK_NB)
        elif scope:
            while True:
                _agent.check_interrupt()
                try:
                    _fcntl.flock(source, _fcntl.LOCK_EX | _fcntl.LOCK_NB)
                    break
                except BlockingIOError:
                    scope.pending.wait(0.1)
            _agent.check_interrupt()
        else:
            _fcntl.flock(source, _fcntl.LOCK_EX)
        yield source


def _send_mail(to: str, subject: str, body: str, *, sender=None, agent_dir=None):
    """Send mail to an existing agent name, or to user. Sender defaults to current agent."""
    if to is None:
        to = "user"
    if isinstance(to, str):
        to = to.strip()
        if to.casefold() == "user":
            to = "user"
    agent_dir = _agent.AGENT_DIR if agent_dir is None else agent_dir
    sender = sender or _os.path.basename(_os.path.normpath(agent_dir))
    for value in (to, subject, sender):
        if any(c in value for c in "\r\n\0"):
            raise ValueError("Invalid mail header")
    root = _os.path.dirname(_os.path.abspath(agent_dir))
    if not to or "\\" in to or to in (".", "..") or _os.path.basename(to) != to:
        raise ValueError("Invalid recipient")
    unknown_recipient = False
    if to == "user":
        directory = root
    else:
        directory = _os.path.join(root, to)
        if (not _os.path.isdir(directory) or
                _os.path.realpath(directory) != _os.path.join(_os.path.realpath(root), to)):
            directory = root
            unknown_recipient = True
    message = _EmailMessage()
    message["From"], message["To"], message["Subject"] = sender, to, subject
    message["X-Agent-Sender"] = sender
    message["Date"] = _formatdate(localtime=True)
    message["Message-ID"] = _make_msgid(domain=sender)
    # Avoid irreversible mbox From-line escaping in newly written messages.
    if re.search(r"^From ", body, re.MULTILINE):
        message.set_content(body, cte="base64")
    else:
        message.set_content(body)
    path = _os.path.join(directory, "mbox")
    # Lock the stable mailbox inode for both delivery and consumption. No rename.
    with _locked_mailbox(path, "a+b"):
        box = _mailbox.mbox(path)
        try:
            entry = _mailbox.mboxMessage(message)
            entry.set_from(sender)
            box.add(entry)
            box.flush()
        finally:
            box.close()
    if unknown_recipient:
        return f"Warning: recipient '{to}' not found; message sent to user."
    return f"Mail sent to {to}."


def _read_mailbox(user=False):
    """Read user mail without consuming it; read and truncate current agent mail."""
    directory = _os.path.dirname(_os.path.abspath(_agent.AGENT_DIR)) if user else _agent.AGENT_DIR
    try:
        with _locked_mailbox(_os.path.join(directory, "mbox"), "r+b") as source:
            text = source.read().decode("utf8", errors="replace")
            if not user:
                source.seek(0)
                source.truncate()
            return text
    except FileNotFoundError:
        return ""


def _mailbox_entries(source, message_id=None):
    """Read exact mbox spans under the caller's mailbox lock."""
    source.seek(0)
    data = source.read()
    snapshot = data
    if message_id is not None:
        try:
            _, _, _, length, _ = message_id.split(":")
            length = int(length)
        except (AttributeError, TypeError, ValueError):
            return data, []
        if length < 0 or length > len(data):
            return data, []
        snapshot = data[:length]
    digest = _hashlib.sha256(snapshot).hexdigest()
    starts = []
    offset = 0
    for line in snapshot.split(b"\n"):
        if line.startswith(b"From "):
            starts.append(offset)
        offset += len(line) + 1
    identity = _os.fstat(source.fileno())
    entries = []
    for start, end in zip(starts, starts[1:] + [len(snapshot)]):
        raw = snapshot[start:end]
        key = f"{identity.st_dev}:{identity.st_ino}:{start}:{len(snapshot)}:{digest}"
        entries.append((key, start, end, raw))
    return data, entries


def _mailbox_message(entry):
    key, start, end, raw = entry
    message = _BytesParser(policy=_policy.default).parsebytes(raw.partition(b"\n")[2])
    body = message.get_body(preferencelist=("plain", "html"))
    text = ""
    if body is not None:
        payload = body.get_payload(decode=True)
        if payload is not None:
            try:
                text = payload.decode(body.get_content_charset() or "ascii", errors="replace")
            except LookupError:
                text = payload.decode("utf8", errors="replace")
    sender = str(message.get("X-Agent-Sender", ""))
    return {"id": key, "from": sender or str(message.get("From", "")),
            "sender": sender,
            "to": str(message.get("To", "")),
            "subject": str(message.get("Subject", "")),
            "date": str(message.get("Date", "")), "body": text}


def _list_mailbox(user=True, *, agent_dir=None, nonblocking=False):
    """List decoded messages without consuming mail. IDs survive append-only delivery."""
    agent_dir = _agent.AGENT_DIR if agent_dir is None else agent_dir
    directory = _os.path.dirname(_os.path.abspath(agent_dir)) if user else agent_dir
    try:
        with _locked_mailbox(_os.path.join(directory, "mbox"), "rb",
                             nonblocking=nonblocking) as source:
            return [_mailbox_message(entry) for entry in _mailbox_entries(source)[1]]
    except FileNotFoundError:
        return []


def _read_mailbox_message(message_id, user=True, *, agent_dir=None, nonblocking=False):
    """Read a listed message; reject missing or changed message IDs."""
    agent_dir = _agent.AGENT_DIR if agent_dir is None else agent_dir
    directory = _os.path.dirname(_os.path.abspath(agent_dir)) if user else agent_dir
    try:
        with _locked_mailbox(_os.path.join(directory, "mbox"), "rb",
                             nonblocking=nonblocking) as source:
            for entry in _mailbox_entries(source, message_id)[1]:
                if entry[0] == message_id:
                    return _mailbox_message(entry)
    except FileNotFoundError:
        pass
    raise ValueError("Mail message is stale or missing")


def _delete_mailbox_message(message_id, user=True, *, agent_dir=None):
    """Delete one unchanged message in place, preserving retained bytes and inode."""
    agent_dir = _agent.AGENT_DIR if agent_dir is None else agent_dir
    directory = _os.path.dirname(_os.path.abspath(agent_dir)) if user else agent_dir
    try:
        with _locked_mailbox(_os.path.join(directory, "mbox"), "r+b") as source:
            data, entries = _mailbox_entries(source, message_id)
            for key, start, end, raw in entries:
                if key == message_id:
                    source.seek(start)
                    source.write(data[end:])
                    source.truncate(start + len(data) - end)
                    source.flush()
                    return True
    except FileNotFoundError:
        pass
    raise ValueError("Mail message is stale or missing")

# Explicit opt-in for depth-0 non-quick supervisors.
mail.supervisor = True
readmail.supervisor = True


def _reply_fields(message):
    subject = message.get("subject", "")
    if not subject.upper().startswith("RE:"):
        subject = "RE: " + subject
    body = "\n\nOn the previous message:\n" + "\n".join(
        "> " + line for line in message.get("body", "").splitlines())
    if message.get("sender"):
        return message["sender"], subject, body
    sender = message.get("from", "").strip()
    match = re.search(r"<([^<>]+)>", sender)
    return match.group(1).strip() if match else sender, subject, body


def cmd_readmail(agent, arg, *, input=None, tk_root=None):
    """Read user mail; CLI supports list, read ID, reply ID, and delete ID."""
    bridge = getattr(tk_root, "__dict__", {}).get("_agent_ui") if tk_root is not None else None
    if bridge is not None:
        return bridge.call(bridge.module(__name__), "_frontend_readmail", {"arg": arg})
    action, _, message_id = arg.strip().partition(" ")
    if not action:
        print(_read_mailbox(user=True))
        return
    try:
        if action == "list":
            for message in _list_mailbox():
                print(message["id"], message["from"], message["subject"])
        elif action == "read":
            message = _read_mailbox_message(message_id.strip())
            print("\n".join(label + ": " + message.get(key, "") for label, key in
                  (("From", "from"), ("To", "to"), ("Subject", "subject"), ("Date", "date"))))
            print("\n" + message["body"])
        elif action == "delete":
            _delete_mailbox_message(message_id.strip())
            print("Mail deleted.")
        elif action == "reply":
            message = _read_mailbox_message(message_id.strip())
            recipient, subject, quoted = _reply_fields(message)
            if input is None:
                print("Reply requires an interactive CLI session.")
                return
            body = _agent._command_editor(quoted, input, tk_root)
            if body is not None:
                print(_send_mail(recipient, subject, body, sender="user"))
        else:
            print("Usage: /readmail [list|read ID|reply ID|delete ID]")
    except (ValueError, OSError) as exc:
        print(f"Mail failed: {exc}")


def cmd_compose(agent, arg, *, input=None, tk_root=None):
    """Compose user mail to an agent with an injected interactive input or GUI."""
    bridge = getattr(tk_root, "__dict__", {}).get("_agent_ui") if tk_root is not None else None
    if bridge is not None:
        return bridge.call(bridge.module(__name__), "_frontend_compose", {"arg": arg})
    to = arg.strip()
    if input is None and (tk_root is None or _agent.input_callback is None):
        print('Mail requires an interactive CLI or GUI session for subject and body.')
        return
    if not to:
        to = _agent._command_input('Recipient: ', input, tk_root).strip()
    if not to:
        return
    subject = _agent._command_input('Subject: ', input, tk_root)
    body = _agent._command_editor('', input, tk_root)
    if body is None:
        return
    try:
        print(_send_mail(to, subject, body, sender="user"))
    except (ValueError, OSError) as e:
        print(f'Mail failed: {e}')


def cmd_mail(agent, arg, *, input=None, tk_root=None):
    """Compatibility: read user mail, or compose mail to the supplied recipient."""
    command = cmd_compose if arg.strip() else cmd_readmail
    return command(agent, arg, input=input, tk_root=tk_root)


def _frontend_readmail(*, tk_root, bridge, arg=""):
    """Open user mail on the injected frontend root."""
    return _mailbox_ui(tk_root, bridge).readmail()


def _frontend_compose(*, tk_root, bridge, arg=""):
    """Compose user mail on the injected frontend root."""
    return _mailbox_ui(tk_root, bridge).compose(arg.strip())


def _frontend_mail(*, tk_root, bridge, arg=""):
    """Compatibility frontend operation for /mail."""
    handler = _frontend_compose if arg.strip() else _frontend_readmail
    return handler(tk_root=tk_root, bridge=bridge, arg=arg)


def _backend_recipients(*, agent_dir):
    """List recipients in the explicitly selected workspace."""
    agent_root = _os.path.dirname(_os.path.abspath(agent_dir))
    try:
        names = _os.listdir(agent_root)
    except OSError:
        names = []
    return ["user"] + sorted(name for name in names
        if _os.path.isdir(_os.path.join(agent_root, name)) and
        _os.path.realpath(_os.path.join(agent_root, name)) ==
        _os.path.join(_os.path.realpath(agent_root), name)) + ["Custom..."]


def _backend_send(*, agent_dir, to, subject, body):
    """Send user mail without retaining frontend state."""
    return _send_mail(to, subject, body, sender="user", agent_dir=agent_dir)


def _backend_mailbox(*, agent_dir, action, message_id=None):
    """Read or update user mail; return data and a recoverable error."""
    try:
        if action == "read":
            return _read_mailbox_message(message_id, agent_dir=agent_dir), None
        if action == "delete":
            _delete_mailbox_message(message_id, agent_dir=agent_dir)
        elif action != "list":
            raise ValueError("Invalid mailbox action")
        return _list_mailbox(agent_dir=agent_dir), None
    except (Exception, KeyboardInterrupt) as exc:
        error = str(exc) or "Mail operation interrupted"
        try:
            return _list_mailbox(agent_dir=agent_dir), error
        except Exception:
            return None, error


_ui = None


def _mailbox_ui(root, bridge):
    global _ui
    if _ui is None:
        _ui = MailboxUI(root, bridge)
    return _ui


class MailboxUI:
    """Mail-owned windows. The frontend bridge marshals Tk calls and worker jobs."""

    def __init__(self, root, bridge):
        import tkinter as tk
        from tkinter import ttk
        self.root, self.bridge = root, bridge
        self.module = bridge.module(__name__)
        self.tk, self.ttk = tk, ttk
        self.session = None
        self.windows = []
        self.closed = False
        self.directory = bridge.workspace["paths"]["AGENT_DIR"]
        self.mutation_controls = []
        self.state_binding = root.bind("<<AgentStateChanged>>",
                                       lambda event: self.refresh_controls(), add="+")

    def active(self):
        return (not self.closed and
                self.directory == self.bridge.workspace["paths"]["AGENT_DIR"])

    def refresh_controls(self):
        available = self.active() and self.bridge.available()
        controls = []
        for button in self.mutation_controls:
            if button.winfo_exists():
                button.configure(state="normal" if available else "disabled")
                controls.append(button)
        self.mutation_controls = controls

    def compose(self, to=""):
        if self.active() and self.bridge.frontend_available():
            return self.dialog(self.root, "Compose", to)

    def dialog(self, parent, title, to="", subject="", body=""):
        tk, ttk = self.tk, self.ttk
        window = tk.Toplevel(parent)
        self.windows.append(window)
        window.title(title)
        window.transient(parent)
        tk.Label(window, text="Recipient").grid(row=0, column=0, sticky="w")
        to_field = ttk.Combobox(window, width=60, values=["user", "Custom..."])
        to_field.configure(values=_backend_recipients(agent_dir=self.directory))
        to_field.grid(row=0, column=1, sticky="ew")
        to_field.insert(0, to)
        def custom_recipient(event):
            if to_field.get() == "Custom...":
                to_field.set("")
                to_field.focus_set()
        to_field.bind("<<ComboboxSelected>>", custom_recipient)
        tk.Label(window, text="Subject").grid(row=1, column=0, sticky="w")
        subject_field = tk.Entry(window, width=60)
        subject_field.grid(row=1, column=1, sticky="ew")
        subject_field.insert(0, subject)
        body_field = tk.Text(window, width=70, height=20, wrap="word")
        body_field.grid(row=2, column=0, columnspan=2, sticky="nsew")
        body_field.insert("1.0", body)
        window.columnconfigure(1, weight=1)
        window.rowconfigure(2, weight=1)
        def send():
            recipient = to_field.get().strip()
            if not recipient:
                window.destroy()
                return
            if not self.bridge.available():
                return
            if not self.active():
                return
            values = {"agent_dir": self.directory, "to": recipient,
                      "subject": subject_field.get(), "body": body_field.get("1.0", "end-1c")}
            if self.bridge.submit(self.module, "_backend_send", values,
                                  lambda result, error: self.result(None, "send", result, error)):
                window.destroy()
        send_button = tk.Button(window, text="Send", command=send)
        send_button.grid(row=3, column=1, sticky="e")
        self.mutation_controls.append(send_button)
        self.refresh_controls()
        window.protocol("WM_DELETE_WINDOW", window.destroy)
        window.bind("<Escape>", lambda event: window.destroy())
        return window

    def request(self, session, action, message_id=None):
        available = (self.bridge.available() if action == "delete" else
                     self.bridge.frontend_available())
        if (not self.active() or not available or session is not self.session or
                not session["window"].winfo_exists() or session["busy"]):
            return False
        session["busy"] = True
        session["status"].set("Loading")
        if action != "delete":
            try:
                if action == "read":
                    result = _read_mailbox_message(message_id, agent_dir=self.directory,
                                                   nonblocking=True)
                else:
                    result = _list_mailbox(agent_dir=self.directory, nonblocking=True)
            except BlockingIOError:
                self.result(session, action, None, "Mailbox busy. Use Refresh to retry.")
            except (ValueError, OSError) as exc:
                self.result(session, action, None, str(exc))
            else:
                self.result(session, action, result, None)
            return
        def done(result, error):
            if error:
                self.result(session, action, None, error)
            else:
                self.result(session, action, *result)
        return self.bridge.submit(self.module, "_backend_mailbox",
                           {"agent_dir": self.directory, "action": action,
                            "message_id": message_id}, done)

    def readmail(self):
        if not self.active() or not self.bridge.frontend_available():
            return
        if self.session is not None and self.session["window"].winfo_exists():
            self.session["window"].lift()
            return
        tk, ttk = self.tk, self.ttk
        window = tk.Toplevel(self.root)
        self.windows.append(window)
        window.title("Readmail")
        window.geometry("760x400")
        table = ttk.Treeview(window, columns=("sender", "subject", "body"),
                             show="headings", selectmode="browse")
        for column, label, width in (("sender", "Sender", 100),
                                     ("subject", "Subject", 200),
                                     ("body", "Body", 500)):
            table.heading(column, text=label)
            table.column(column, width=width, stretch=False)
        scroll = ttk.Scrollbar(window, command=table.yview)
        table.configure(yscrollcommand=scroll.set)
        scroll.pack(side="right", fill="y")
        table.pack(fill="both", expand=True)
        state = tk.StringVar(value="")
        tk.Label(window, textvariable=state, anchor="w").pack(fill="x")
        session = {"window": window, "tree": table, "status": state, "busy": False,
                   "rows": {}}
        self.session = session
        def selected(action):
            selection = table.selection()
            if selection:
                self.request(session, action, session["rows"].get(selection[0]))
            return "break"
        controls = tk.Frame(window)
        controls.pack(fill="x")
        for label, action in (("Read", "read"), ("Delete", "delete")):
            button = tk.Button(controls, text=label, command=lambda action=action: selected(action))
            button.pack(side="left")
            if action == "delete":
                self.mutation_controls.append(button)
        tk.Button(controls, text="Refresh",
                  command=lambda: self.request(session, "list")).pack(side="left")
        self.refresh_controls()
        table.bind("<Double-1>", lambda event: selected("read"))
        table.bind("<Return>", lambda event: selected("read"))
        table.bind("<Delete>", lambda event: selected("delete"))
        window.bind("<Escape>", lambda event: window.destroy())
        self.request(session, "list")

    def close(self):
        self.closed = True
        if self.state_binding:
            self.root.unbind("<<AgentStateChanged>>", self.state_binding)
            self.state_binding = None
        self.mutation_controls.clear()
        for window in self.windows:
            if window.winfo_exists():
                window.destroy()
        self.windows.clear()
        self.session = None

    def result(self, session, action, result, error):
        if not self.active():
            return
        if session is None:
            self.bridge.output(("Mail send failed: " + str(error) if error else
                                str(result or "Mail sent.")) + "\n")
            return
        if session is not self.session or not session["window"].winfo_exists():
            return
        session["busy"] = False
        session["status"].set(str(error) if error else "")
        if action == "read" and not error:
            tk, ttk = self.tk, self.ttk
            window = tk.Toplevel(session["window"])
            self.windows.append(window)
            window.title("Message")
            window.geometry("700x500")
            controls = tk.Frame(window)
            controls.pack(side="bottom", fill="x")
            text = tk.Text(window, wrap="word")
            scroll = ttk.Scrollbar(window, command=text.yview)
            text.configure(yscrollcommand=scroll.set)
            scroll.pack(side="right", fill="y")
            text.pack(fill="both", expand=True)
            text.insert("1.0", "\n".join(label + ": " + result.get(key, "") for label, key in
                        (("From", "from"), ("To", "to"), ("Subject", "subject"), ("Date", "date")))
                        + "\n\n" + result["body"])
            text.configure(state="disabled")
            def reply():
                if not self.active() or not self.bridge.frontend_available():
                    return
                recipient, subject, body = _reply_fields(result)
                self.dialog(window, "Reply", recipient, subject, body)
            def delete_message():
                if not self.bridge.available():
                    return
                if self.request(session, "delete", result.get("id")):
                    window.destroy()
            tk.Button(controls, text="Reply", command=reply).pack(side="left")
            button = tk.Button(controls, text="Delete", command=delete_message)
            button.pack(side="left")
            self.mutation_controls.append(button)
            self.refresh_controls()
            window.bind("<Escape>", lambda event: window.destroy())
        elif action != "send" and result is not None:
            table = session["tree"]
            table.delete(*table.get_children())
            session["rows"].clear()
            for message in result:
                row = table.insert("", "end", values=(message.get("from", "")[:10],
                                                       message.get("subject", "")[:20],
                                                       message.get("body", "")[:50]))
                session["rows"][row] = message["id"]


def _close_ui(tk_root, *, bridge=None):
    global _ui
    if _ui is not None:
        _ui.close()
        _ui = None


cmd_readmail.ui = {"menu": "Mail", "label": "Readmail", "direct": True,
                   "frontend": "_frontend_readmail", "cleanup": "_close_ui",
                   "safe_during_inference": True}
cmd_compose.ui = {"menu": "Mail", "label": "Compose…", "direct": True,
                  "frontend": "_frontend_compose", "cleanup": "_close_ui",
                  "safe_during_inference": True}

cmd_mail.ui = {"hidden": True, "frontend": "_frontend_mail", "cleanup": "_close_ui",
               "safe_during_inference": True}
