import argparse

from falcorn import ControlClient


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Falcorn control plugin client (SDK)")
    parser.add_argument("--socket", default=None, help="Control socket path")
    parser.add_argument("--token", default=None, help="Auth token")
    parser.add_argument("--client-name", default=None, help="Client name")
    parser.add_argument(
        "--action",
        default="status",
        choices=[
            "status",
            "workers",
            "show-config",
            "scale",
            "restart",
            "shutdown",
            "reload",
        ],
    )
    parser.add_argument("--workers", type=int, default=None, help="Worker count for scale")
    parser.add_argument("--id", type=int, default=None, help="Worker id for restart")
    parser.add_argument("--force", action="store_true", help="Force restart/shutdown")
    parser.add_argument("--path", default=None, help="Config path for reload")
    parser.add_argument("--no-rolling", action="store_true", help="Disable rolling reload")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    client = ControlClient(
        socket=args.socket,
        auth_token=args.token,
        client_name=args.client_name,
    )

    if args.action == "status":
        print(client.get_status())
    elif args.action == "workers":
        print(client.get_workers())
    elif args.action == "show-config":
        print(client.show_config())
    elif args.action == "scale":
        if args.workers is None:
            raise SystemExit("--workers is required for scale")
        print(client.scale_to(args.workers))
    elif args.action == "restart":
        print(client.restart_worker(args.id, graceful=not args.force))
    elif args.action == "shutdown":
        print(client.shutdown(graceful=not args.force))
    elif args.action == "reload":
        print(client.reload_config(args.path, rolling=not args.no_rolling))


if __name__ == "__main__":
    main()
