"""Command-line interface for RunSentry agent."""

import argparse
import sys
from runsentry.daemon import run_daemon
from runsentry.exec import run_exec
from runsentry.auth import register_agent
from runsentry import __version__


def main():
    """Main CLI entrypoint."""
    parser = argparse.ArgumentParser(
        description="RunSentry Agent - Monitor scheduled jobs",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Commands:
  daemon      Run agent daemon (continuous discovery and sync)
  exec        Execute and track a job execution
  register    Register agent with backend (internal, used by install.sh)
        """.strip(),
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"%(prog)s {__version__}",
    )

    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    # Daemon command
    daemon_parser = subparsers.add_parser(
        "daemon",
        help="Run agent daemon (for continuous operation)",
    )
    daemon_parser.set_defaults(func=lambda args: run_daemon())

    # Exec command
    exec_parser = subparsers.add_parser(
        "exec",
        help="Execute and track a job execution",
    )
    exec_parser.add_argument(
        "command_args",
        nargs=argparse.REMAINDER,
        help="Command and arguments to execute",
    )
    exec_parser.set_defaults(
        func=lambda args: run_exec(args.command_args) if args.command_args else (
            print("Error: exec requires a command to run", file=sys.stderr),
            sys.exit(1)
        )[1]
    )

    # Register command (internal, used by install.sh)
    register_parser = subparsers.add_parser(
        "register",
        help="Register agent with RunSentry backend (internal use)",
        description="Internal command used by install.sh. Not intended for direct use.",
    )
    register_parser.add_argument(
        "--token",
        required=True,
        help="Registration token",
    )
    register_parser.add_argument(
        "--backend-url",
        default="https://runsentry-api.azurewebsites.net/",
        help="Backend URL (default: https://runsentry-api.azurewebsites.net/)",
    )
    register_parser.add_argument(
        "--agent-name",
        help="Agent name (default: hostname)",
    )
    register_parser.add_argument(
        "--retries",
        type=int,
        default=3,
        help="Number of registration retry attempts (default: 3)",
    )
    register_parser.set_defaults(
        func=lambda args: (
            sys.exit(0) if register_agent(
                token=args.token,
                backend_url=args.backend_url,
                agent_name=args.agent_name,
                retries=args.retries,
            ) else sys.exit(1)
        )
    )

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(1)

    try:
        args.func(args)
    except KeyboardInterrupt:
        print("\nInterrupted by user", file=sys.stderr)
        sys.exit(130)
    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
