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

Usage:
    onefirewall-ai                                       → interactive agent REPL
    onefirewall-ai help                                  → help
    onefirewall-ai version                               → version
    onefirewall-ai login                                 → login flow

    onefirewall-ai sessions                              → list all sessions
    onefirewall-ai sessions view <id>                    → view session history

    onefirewall-ai agent <task...>                       → new agent session
    onefirewall-ai --agent <task...>                     → same
    onefirewall-ai chat <message...>                     → explicit chat mode
    onefirewall-ai --chat <message...>                   → same
    onefirewall-ai --session <id> agent <task...>        → resume session in agent mode
    onefirewall-ai --session <name> agent <task...>      → start/resume named session

    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."""
    init_home()

    args = sys.argv[1:]

    # ── Help/Version ──────────────────────────────────────────────────────────
    if args and args[0] in ("help", "--help", "-h"):
        from onefirewall_ai.utils import print_help
        print_help()
        return

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

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

    # ── Sessions ──────────────────────────────────────────────────────────────
    # onefirewall-ai sessions            → list
    # onefirewall-ai sessions view <id>  → full history of a session
    if args and args[0] == "sessions":
        if len(args) >= 3 and args[1] == "view":
            from onefirewall_ai.sessions import view_session
            view_session(args[2])
        else:
            from onefirewall_ai.sessions import list_sessions
            list_sessions()
        return

    # ── --session flag — parse FIRST so it works in any position ─────────────
    # Works in all of these forms:
    #   onefirewall-ai --session myapp agent "task"   ← before agent
    #   onefirewall-ai agent --session myapp "task"   ← after agent
    #   onefirewall-ai --session myapp "chat message" ← chat mode
    session_id = None
    if "--session" in args:
        idx = args.index("--session")
        if idx + 1 < len(args):
            session_id = args[idx + 1]
            args = args[:idx] + args[idx + 2:]

    # ── Interaction mode — checked AFTER session stripped ─────────────────────
    # onefirewall-ai agent "task"
    # onefirewall-ai --session myapp agent "task"  ("agent" now at index 0 after strip)
    # onefirewall-ai chat "message"
    # onefirewall-ai --chat "message"
    agent_mode = False
    explicit_mode = False
    if args and args[0] in ("agent", "--agent"):
        agent_mode = True
        explicit_mode = True
        args = args[1:]
    elif args and args[0] in ("chat", "--chat"):
        agent_mode = False
        explicit_mode = True
        args = args[1:]

    # ── Piped stdin ───────────────────────────────────────────────────────────
    piped_content = ""
    if not sys.stdin.isatty():
        try:
            piped_content = sys.stdin.read().strip()
        except Exception as e:
            print(f"[WARNING] Could not read piped input: {e}")

    prompt_text = " ".join(args).strip()

    # Combine prompt + piped input
    parts = []
    if piped_content:
        parts.append(f"Piped Input:\n---\n{piped_content}\n---")
    if prompt_text:
        parts.append(prompt_text)

    prompt = "\n\n".join(parts).strip()

    if prompt:
        if agent_mode:
            from onefirewall_ai.agent.loop import run_agent
            run_agent(prompt, session_id=session_id)
        else:
            from onefirewall_ai.chat import send
            send(prompt, session_id=session_id)
        return

    # ── Interaction mode (REPL) ───────────────────────────────────────────────
    # If no prompt was provided (e.g. `onefirewall-ai` or `onefirewall-ai agent`),
    # launch the interactive REPL and start directly in agent mode unless
    # the user explicitly asked for chat mode.
    from onefirewall_ai.repl import run_repl
    run_repl(
        initial_prompt=None,
        session_id=session_id,
        agent_mode=agent_mode if explicit_mode else True,
    )


if __name__ == "__main__":
    main()
