"""ACTA CLI — file-based async message passing for AI agents."""

import argparse
import sys
from haeres.board import post, read, clear, clear_all, archive, archive_all, count


def cmd_list(args):
    msgs = read(to=args.to)
    if not msgs:
        print("Board empty." if not args.to else f"No messages for '{args.to}'.")
        return
    label = f" (to: {args.to})" if args.to else ""
    print(f"{len(msgs)} message(s){label}:\n")
    for m in msgs:
        sev = m.get("severity", "info")
        sender = m.get("from", "?")
        recipient = m.get("to", "all")
        marker = {"action": "!", "warning": "~", "info": " "}.get(sev, " ")
        body_preview = m.get("body", "")[:100].replace("\n", " ")
        print(f"  [{marker}] {m['id']}")
        print(f"      {sender} → {recipient} | {body_preview}")
        print()


def cmd_post(args):
    path = post(
        message=args.message,
        sender=args.sender,
        to=args.to,
        severity=args.severity,
        subject=args.subject,
    )
    print(f"Posted: {path.name}")


def cmd_clear(args):
    if args.all:
        print(f"Cleared {clear_all()} message(s).")
    elif args.id:
        if clear(args.id):
            print(f"Cleared: {args.id}")
        else:
            print(f"Not found: {args.id}", file=sys.stderr)
            sys.exit(1)
    else:
        print("Specify <id> or --all", file=sys.stderr)
        sys.exit(1)


def cmd_archive(args):
    if args.all:
        print(f"Archived {archive_all()} message(s).")
    elif args.id:
        if archive(args.id):
            print(f"Archived: {args.id}")
        else:
            print(f"Not found: {args.id}", file=sys.stderr)
            sys.exit(1)
    else:
        print("Specify <id> or --all", file=sys.stderr)
        sys.exit(1)


def cmd_count(_args):
    print(count())


def main():
    parser = argparse.ArgumentParser(description="ACTA — file-based async message passing for AI agents")
    sub = parser.add_subparsers(dest="command")

    p_list = sub.add_parser("list", help="List messages")
    p_list.add_argument("--to", default=None, help="Filter by recipient")

    p_post = sub.add_parser("post", help="Post a message")
    p_post.add_argument("message", help="Message body")
    p_post.add_argument("--from", dest="sender", default="cli", help="Sending skill")
    p_post.add_argument("--to", default="all", help="Recipient (skill name, human, or all)")
    p_post.add_argument("--severity", "-v", default="info", choices=["action", "info", "warning"])
    p_post.add_argument("--subject", "-t", default=None, help="Subject slug")

    p_clear = sub.add_parser("clear", help="Clear message(s)")
    p_clear.add_argument("id", nargs="?", help="Message ID")
    p_clear.add_argument("--all", action="store_true")

    p_archive = sub.add_parser("archive", help="Archive message(s)")
    p_archive.add_argument("id", nargs="?", help="Message ID")
    p_archive.add_argument("--all", action="store_true")

    sub.add_parser("count", help="Count unread messages")

    args = parser.parse_args()

    if args.command is None or args.command == "list":
        cmd_list(args)
    elif args.command == "post":
        cmd_post(args)
    elif args.command == "clear":
        cmd_clear(args)
    elif args.command == "archive":
        cmd_archive(args)
    elif args.command == "count":
        cmd_count(args)
