"""CLI entry point: easyclaw install / easyclaw help / easyclaw agent / easyclaw (REPL)."""

from __future__ import annotations

import argparse
import sys


def main() -> None:
    parser = argparse.ArgumentParser(
        prog="easyclaw",
        description="EasyClaw — AI Agent for OpenClaw",
    )
    # Top-level flags for bare `easyclaw` REPL mode
    parser.add_argument(
        "--api-key", default="", help="EasyClaw API key (ec_live_...)"
    )
    parser.add_argument(
        "--openrouter-key", default="", help="OpenRouter API key (sk-or-...)"
    )

    sub = parser.add_subparsers(dest="command")

    # easyclaw install
    install_p = sub.add_parser("install", help="Run the interactive installer")
    install_p.add_argument("--api-key", default="", help="EasyClaw API key (ec_live_...)")
    install_p.add_argument("--openrouter-key", default="", help="OpenRouter API key (sk-or-...)")
    install_p.add_argument("--openai-key", default="", help="OpenAI API key (optional, for memory)")
    install_p.add_argument("--model", default="", help="Primary model (default: free built-in)")
    install_p.add_argument("--channel", default="none", help="Channel: none, whatsapp, telegram, discord")
    install_p.add_argument("--bind", default="lan", help="Bind mode: lan, loopback, auto, tailnet")
    install_p.add_argument("--no-tui", action="store_true", help="Fall back to bash script")

    # easyclaw help
    sub.add_parser("help", help="Post-install troubleshooting (TUI)")

    # easyclaw agent
    agent_p = sub.add_parser("agent", help="Foreman AI agent (daemon management)")
    agent_sub = agent_p.add_subparsers(dest="agent_command")

    # easyclaw agent start
    start_p = agent_sub.add_parser("start", help="Start the health monitor daemon")
    start_p.add_argument("--interval", type=int, default=60, help="Health check interval in seconds")
    start_p.add_argument("--foreground", action="store_true", help="Run in foreground (for systemd)")
    start_p.add_argument("--api-key", default="", help="EasyClaw API key")
    start_p.add_argument("--openrouter-key", default="", help="OpenRouter API key")

    # easyclaw agent stop
    agent_sub.add_parser("stop", help="Stop the daemon")

    # easyclaw agent status
    agent_sub.add_parser("status", help="Show daemon status and recent actions")

    # easyclaw agent log
    log_p = agent_sub.add_parser("log", help="Tail the agent log")
    log_p.add_argument("-n", type=int, default=50, help="Number of lines to show")

    # easyclaw agent systemd
    agent_sub.add_parser("systemd", help="Install systemd service for the agent")

    args = parser.parse_args()

    # ----- Route commands -----

    if args.command is None:
        # Bare `easyclaw` → launch the Foreman REPL
        _run_agent_repl(
            api_key=getattr(args, "api_key", ""),
            openrouter_key=getattr(args, "openrouter_key", ""),
        )

    elif args.command == "install":
        if getattr(args, "no_tui", False):
            print("Falling back to bash installer...")
            print("Run: curl -fsSL https://easyclaw.help/install.sh | bash")
            sys.exit(0)
        _run_install(
            api_key=getattr(args, "api_key", ""),
            openrouter_key=getattr(args, "openrouter_key", ""),
            openai_key=getattr(args, "openai_key", ""),
            model=getattr(args, "model", ""),
            channel=getattr(args, "channel", "none"),
            bind=getattr(args, "bind", "lan"),
        )

    elif args.command == "help":
        _run_help()

    elif args.command == "agent":
        _handle_agent(args)

    else:
        parser.print_help()


def _run_install(
    api_key: str = "",
    openrouter_key: str = "",
    openai_key: str = "",
    model: str = "minimax-m2.5",
    channel: str = "none",
    bind: str = "lan",
) -> None:
    from easyclaw_tui.app import EasyClawApp

    app = EasyClawApp(
        mode="install",
        api_key=api_key,
        openrouter_key=openrouter_key,
        openai_key=openai_key,
        model=model,
        channel=channel,
        bind=bind,
    )
    result = app.run()

    # After install completes, launch the Foreman agent REPL
    if result == "install_complete":
        _run_agent_repl(api_key=api_key, openrouter_key=openrouter_key)


def _run_help() -> None:
    from easyclaw_tui.app import EasyClawApp

    app = EasyClawApp(mode="help")
    app.run()


def _run_agent_repl(api_key: str = "", openrouter_key: str = "") -> None:
    """Launch the Foreman REPL (interactive agent prompt)."""
    import asyncio

    from easyclaw_tui.agent.config import AgentConfig
    from easyclaw_tui.agent.repl import run_repl

    config = AgentConfig.load()
    config.resolve_keys(cli_api_key=api_key, cli_or_key=openrouter_key)
    config.save()

    asyncio.run(run_repl(config))


def _handle_agent(args: argparse.Namespace) -> None:
    """Handle `easyclaw agent <subcommand>`."""
    from easyclaw_tui.agent.config import AgentConfig
    from easyclaw_tui.agent import daemon

    cmd = getattr(args, "agent_command", None)

    if cmd == "start":
        config = AgentConfig.load()
        config.resolve_keys(
            cli_api_key=getattr(args, "api_key", ""),
            cli_or_key=getattr(args, "openrouter_key", ""),
        )
        config.check_interval = getattr(args, "interval", 60)
        config.save()

        foreground = getattr(args, "foreground", False)
        daemon.start_daemon(config, foreground=foreground)

    elif cmd == "stop":
        daemon.stop_daemon()

    elif cmd == "status":
        daemon.show_status()

    elif cmd == "log":
        n = getattr(args, "n", 50)
        daemon.tail_log(lines=n)

    elif cmd == "systemd":
        daemon.install_systemd()

    else:
        print("Usage: easyclaw agent {start|stop|status|log|systemd}")
        print()
        print("  start    Start the health monitor daemon")
        print("  stop     Stop the daemon")
        print("  status   Show daemon status and recent actions")
        print("  log      Tail the agent log")
        print("  systemd  Install systemd service")


if __name__ == "__main__":
    main()
