"""CLI entry point for zimba."""

import getpass
import json
import sys

from . import __version__


def _out(data):
    """Print JSON output."""
    print(json.dumps(data, indent=2))


def cmd_setup(args):
    """Configure Zimbra credentials."""
    from .api import save_config, get_token

    if len(args) >= 3:
        server, username, password = args[0], args[1], args[2]
    elif len(args) == 2:
        server, username = args[0], args[1]
        password = getpass.getpass("Password: ")
    else:
        server = input("Server URL (e.g. https://mail.example.com): ").strip()
        username = input("Email address: ").strip()
        password = getpass.getpass("Password: ")

    if not server.startswith("http"):
        server = "https://" + server

    save_config(server, username, password)

    try:
        get_token()
        print(f"Authenticated as {username}")
    except RuntimeError as e:
        print(f"Auth failed: {e}", file=sys.stderr)
        sys.exit(1)


def cmd_email(args):
    """Email subcommands."""
    from . import email

    if not args:
        print("Usage: zimba email <search|read|send|reply|forward|folders|move|delete|mark-read|flag>", file=sys.stderr)
        sys.exit(1)

    sub = args[0]
    rest = args[1:]

    if sub == "search":
        query = rest[0] if rest else "in:inbox"
        limit = int(rest[1]) if len(rest) > 1 else 20
        offset = int(rest[2]) if len(rest) > 2 else 0
        _out(email.search(query, limit, offset))

    elif sub == "read":
        if not rest:
            print("Usage: zimba email read <msg_id> [download_dir]", file=sys.stderr)
            sys.exit(1)
        _out(email.read(rest[0], rest[1] if len(rest) > 1 else None))

    elif sub == "send":
        if len(rest) >= 3:
            to, subject, body = rest[0], rest[1], rest[2]
            atts = rest[3:] or None
            _out(email.send(to, subject, body, attachments=atts))
        else:
            data = json.load(sys.stdin)
            _out(email.send(**data))

    elif sub == "reply":
        if len(rest) >= 2:
            msg_id, body = rest[0], rest[1]
            reply_all = "--all" in rest
            atts = [a for a in rest[2:] if a != "--all"] or None
            _out(email.reply(msg_id, body, reply_all=reply_all, attachments=atts))
        else:
            data = json.load(sys.stdin)
            _out(email.reply(**data))

    elif sub == "forward":
        if len(rest) >= 2:
            msg_id, to = rest[0], rest[1]
            body = rest[2] if len(rest) > 2 else ""
            atts = rest[3:] or None
            _out(email.forward(msg_id, to, body, attachments=atts))
        else:
            data = json.load(sys.stdin)
            _out(email.forward(**data))

    elif sub == "folders":
        _out(email.folders())

    elif sub == "move":
        if len(rest) < 2:
            print("Usage: zimba email move <folder_id> <msg_id> [msg_id...]", file=sys.stderr)
            sys.exit(1)
        _out(email.move(rest[1:], rest[0]))

    elif sub == "delete":
        hard = "--hard" in rest
        ids = [a for a in rest if a != "--hard"]
        _out(email.delete(ids, hard=hard))

    elif sub == "mark-read":
        unread = "--unread" in rest
        ids = [a for a in rest if a != "--unread"]
        _out(email.mark_read(ids, read=not unread))

    elif sub == "flag":
        unflag = "--unflag" in rest
        ids = [a for a in rest if a != "--unflag"]
        _out(email.flag(ids, flagged=not unflag))

    else:
        print(f"Unknown email command: {sub}", file=sys.stderr)
        sys.exit(1)


def cmd_calendar(args):
    """Calendar subcommands."""
    from . import calendar

    if not args:
        print("Usage: zimba calendar <events|details|create|update|delete>", file=sys.stderr)
        sys.exit(1)

    sub = args[0]
    rest = args[1:]

    if sub == "events":
        start = int(rest[0]) if rest else None
        end = int(rest[1]) if len(rest) > 1 else None
        _out(calendar.events(start=start, end=end))

    elif sub == "details":
        if not rest:
            print("Usage: zimba calendar details <event_id>", file=sys.stderr)
            sys.exit(1)
        _out(calendar.event_details(rest[0]))

    elif sub == "create":
        data = json.load(sys.stdin)
        _out(calendar.create_event(**data))

    elif sub == "update":
        data = json.load(sys.stdin)
        _out(calendar.update_event(**data))

    elif sub == "delete":
        if not rest:
            print("Usage: zimba calendar delete <event_id>", file=sys.stderr)
            sys.exit(1)
        _out(calendar.delete_event(rest[0]))

    else:
        print(f"Unknown calendar command: {sub}", file=sys.stderr)
        sys.exit(1)


def cmd_contacts(args):
    """Contacts subcommands."""
    from . import contacts

    if not args:
        print("Usage: zimba contacts <search|get|create|update|delete>", file=sys.stderr)
        sys.exit(1)

    sub = args[0]
    rest = args[1:]

    if sub == "search":
        query = rest[0] if rest else "*"
        limit = int(rest[1]) if len(rest) > 1 else 50
        _out(contacts.search(query, limit))

    elif sub == "get":
        if not rest:
            print("Usage: zimba contacts get <contact_id>", file=sys.stderr)
            sys.exit(1)
        _out(contacts.get(rest[0]))

    elif sub == "create":
        data = json.load(sys.stdin)
        _out(contacts.create(**data))

    elif sub == "update":
        data = json.load(sys.stdin)
        _out(contacts.update(**data))

    elif sub == "delete":
        if not rest:
            print("Usage: zimba contacts delete <contact_id>", file=sys.stderr)
            sys.exit(1)
        _out(contacts.delete(rest[0]))

    else:
        print(f"Unknown contacts command: {sub}", file=sys.stderr)
        sys.exit(1)


def main():
    args = sys.argv[1:]
    if not args or args[0] in ("-h", "--help"):
        print(f"zimba {__version__} — CLI for Zimbra email, calendar, and contacts")
        print()
        print("Usage: zimba <command> [args]")
        print()
        print("Commands:")
        print("  setup                  Configure server and credentials")
        print("  email search|read|send|reply|forward|folders|move|delete|mark-read|flag")
        print("  calendar events|details|create|update|delete")
        print("  contacts search|get|create|update|delete")
        print("  version                Show version")
        sys.exit(0)

    cmd = args[0]
    rest = args[1:]

    if cmd == "setup":
        cmd_setup(rest)
    elif cmd == "email":
        cmd_email(rest)
    elif cmd == "calendar":
        cmd_calendar(rest)
    elif cmd == "contacts":
        cmd_contacts(rest)
    elif cmd == "version":
        print(f"zimba {__version__}")
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
