#!/usr/bin/env python3
"""Tiny CLI for the AgentMail inbox (send / list / read email from an AI agent).

Reads ``AGENTMAIL_API_KEY`` and ``AGENTMAIL_INBOX`` from the repo-root ``.env``
(no python-dotenv dependency — a 3-line parser handles it). The inbox address
is ``cosmas-5316@agentmail.to``. Docs: https://docs.agentmail.to

Run from the repo root with the project venv:

    .venv/bin/python scripts/agentmail_cli.py list [--limit N]
    .venv/bin/python scripts/agentmail_cli.py read <message_id>
    .venv/bin/python scripts/agentmail_cli.py send --to a@b.com --subject "Hi" --text "Body"
    .venv/bin/python scripts/agentmail_cli.py send --to a@b.com --subject "Hi" --html "<p>Body</p>"

`send` prints the new message id; `list` prints id / from / subject per row.
"""
from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path

from agentmail import AgentMail

REPO_ROOT = Path(__file__).resolve().parent.parent


def _load_env() -> dict[str, str]:
    """Parse KEY=VALUE lines from the repo-root .env (ignores comments/blanks)."""
    env: dict[str, str] = {}
    env_path = REPO_ROOT / ".env"
    if env_path.exists():
        for line in env_path.read_text().splitlines():
            line = line.strip()
            if line and not line.startswith("#") and "=" in line:
                key, value = line.split("=", 1)
                env[key.strip()] = value.strip()
    # process env wins (e.g. inside Docker) over the .env file
    for key in ("AGENTMAIL_API_KEY", "AGENTMAIL_INBOX"):
        if os.environ.get(key):
            env[key] = os.environ[key]
    return env


def _client_and_inbox() -> tuple[AgentMail, str]:
    env = _load_env()
    api_key = env.get("AGENTMAIL_API_KEY")
    inbox = env.get("AGENTMAIL_INBOX")
    if not api_key or not inbox:
        sys.exit("Missing AGENTMAIL_API_KEY / AGENTMAIL_INBOX (set them in .env).")
    return AgentMail(api_key=api_key), inbox


def cmd_list(args: argparse.Namespace) -> None:
    client, inbox = _client_and_inbox()
    result = client.inboxes.messages.list(inbox, limit=args.limit)
    print(f"{getattr(result, 'count', '?')} message(s) in {inbox}:\n")
    for msg in result.messages:
        sender = getattr(msg, "from_", None) or getattr(msg, "from", "?")
        print(f"  {msg.message_id}")
        print(f"    from:    {sender}")
        print(f"    subject: {getattr(msg, 'subject', None)}\n")


def cmd_read(args: argparse.Namespace) -> None:
    client, inbox = _client_and_inbox()
    msg = client.inboxes.messages.get(inbox, args.message_id)
    sender = getattr(msg, "from_", None) or getattr(msg, "from", "?")
    print(f"From:    {sender}")
    print(f"To:      {getattr(msg, 'to', None)}")
    print(f"Subject: {getattr(msg, 'subject', None)}")
    print("-" * 60)
    print(getattr(msg, "text", None) or getattr(msg, "extracted_text", "") or "(no text body)")


def cmd_send(args: argparse.Namespace) -> None:
    client, inbox = _client_and_inbox()
    if not args.text and not args.html:
        sys.exit("Provide --text and/or --html for the body.")
    result = client.inboxes.messages.send(
        inbox,
        to=args.to,
        subject=args.subject,
        text=args.text,
        html=args.html,
    )
    print(f"Sent. message_id={getattr(result, 'message_id', result)}")


def main() -> None:
    parser = argparse.ArgumentParser(description="AgentMail inbox CLI")
    sub = parser.add_subparsers(dest="cmd", required=True)

    p_list = sub.add_parser("list", help="list recent messages")
    p_list.add_argument("--limit", type=int, default=10)
    p_list.set_defaults(func=cmd_list)

    p_read = sub.add_parser("read", help="print one message body")
    p_read.add_argument("message_id")
    p_read.set_defaults(func=cmd_read)

    p_send = sub.add_parser("send", help="send an email")
    p_send.add_argument("--to", required=True)
    p_send.add_argument("--subject", required=True)
    p_send.add_argument("--text", default=None)
    p_send.add_argument("--html", default=None)
    p_send.set_defaults(func=cmd_send)

    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()
