"""
cli.py — Main entry point and command dispatcher for onefirewall-ai.

Usage:
    onefirewall-ai                                  → help
    onefirewall-ai help                             → help
    onefirewall-ai version                          → version
    onefirewall-ai login                            → login flow
    onefirewall-ai sessions                         → list sessions
    onefirewall-ai [--session ID] <message...>      → stream chat response
"""

import sys

from onefirewall_ai.config import init_home


def main() -> None:
    """Entry point registered in pyproject.toml."""
    # Always ensure ~/.onefirewall-ai/ exists
    init_home()

    args = sys.argv[1:]  # everything after "onefirewall-ai"

    # ── No args or explicit help ───────────────────────────────────────────────
    if not args or args[0] in ("help", "--help", "-h"):
        from onefirewall_ai.utils import print_help
        print_help()
        return

    # ── Version ───────────────────────────────────────────────────────────────
    if args[0] in ("version", "--version", "-v"):
        from onefirewall_ai.utils import print_version
        print_version()
        return

    # ── Login ─────────────────────────────────────────────────────────────────
    if args[0] == "login":
        from onefirewall_ai.auth import login
        login()
        return

    # ── Sessions ──────────────────────────────────────────────────────────────
    if args[0] == "sessions":
        from onefirewall_ai.sessions import list_sessions
        list_sessions()
        return

    # ── Chat — any other argument(s) become the prompt ────────────────────────
    session_id = None
    if "--session" in args:
        idx = args.index("--session")
        if idx + 1 < len(args):
            session_id = args[idx + 1]
            args.pop(idx)
            args.pop(idx)

    prompt = " ".join(args).strip()
    if prompt:
        from onefirewall_ai.chat import send
        send(prompt, session_id=session_id)
        return

    # Fallback
    from onefirewall_ai.utils import print_help
    print_help()


if __name__ == "__main__":
    main()
