"""
Main CLI entry point
"""

import sys


def main():
    """Main CLI entry point"""
    if len(sys.argv) < 2:
        # No arguments - launch TUI
        from ..tui.app import main as tui_main
        tui_main()
        return

    command = sys.argv[1]

    if command == "status":
        from .status import print_status
        print_status()

    elif command == "start":
        if len(sys.argv) < 3:
            print("Usage: infra start <service>")
            sys.exit(1)
        from .service import start_service
        start_service(sys.argv[2])

    elif command == "stop":
        if len(sys.argv) < 3:
            print("Usage: infra stop <service>")
            sys.exit(1)
        from .service import stop_service
        stop_service(sys.argv[2])

    elif command == "restart":
        if len(sys.argv) < 3:
            print("Usage: infra restart <service>")
            sys.exit(1)
        from .service import restart_service
        restart_service(sys.argv[2])

    elif command == "logs":
        if len(sys.argv) < 3:
            print("Usage: infra logs <service>")
            sys.exit(1)
        from .service import logs_service
        logs_service(sys.argv[2])

    elif command == "cloudflare":
        if len(sys.argv) < 3:
            print("Usage: infra cloudflare <subcommand> [options]")
            sys.exit(1)

        subcommand = sys.argv[2]

        if subcommand == "list-domains":
            from .cloudflare import cf_list_domains
            cf_list_domains()

        elif subcommand == "list-records":
            if len(sys.argv) < 4:
                print("Usage: infra cloudflare list-records <domain>")
                sys.exit(1)
            from .cloudflare import cf_list_records
            cf_list_records(sys.argv[3])

        elif subcommand == "add":
            if len(sys.argv) < 7:
                print("Usage: infra cloudflare add <domain> <type> <name> <content>")
                sys.exit(1)
            from .cloudflare import cf_add_record
            cf_add_record(sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6])

        elif subcommand == "configure":
            from .cloudflare import cf_configure
            cf_configure()

        elif subcommand == "test":
            from .cloudflare import cf_test
            cf_test()

        elif subcommand == "list-tokens":
            from .cloudflare import cf_list_tokens
            cf_list_tokens()

        elif subcommand == "add-token":
            if len(sys.argv) < 4:
                print("Usage: infra cloudflare add-token <name>")
                sys.exit(1)
            from .cloudflare import cf_add_token
            cf_add_token(sys.argv[3])

        elif subcommand == "remove-token":
            if len(sys.argv) < 4:
                print("Usage: infra cloudflare remove-token <name>")
                sys.exit(1)
            from .cloudflare import cf_remove_token
            cf_remove_token(sys.argv[3])

        elif subcommand == "test-token":
            if len(sys.argv) < 4:
                print("Usage: infra cloudflare test-token <name>")
                sys.exit(1)
            from .cloudflare import cf_test_token
            cf_test_token(sys.argv[3])

        elif subcommand == "set-service-token":
            if len(sys.argv) < 5:
                print("Usage: infra cloudflare set-service-token <service> <token>")
                sys.exit(1)
            from .cloudflare import cf_set_service_token
            cf_set_service_token(sys.argv[3], sys.argv[4])

        else:
            print(f"Unknown cloudflare subcommand: {subcommand}")
            sys.exit(1)

    elif command == "registry":
        if len(sys.argv) < 3:
            print("Usage: infra registry <subcommand> [options]")
            print("\nSubcommands:")
            print("  list [--infrastructure|--services]  - List available stacks")
            print("  install <name> [-e KEY=VALUE ...]   - Install a stack")
            print("  uninstall <name>                    - Uninstall a stack")
            print("  enable <name>                       - Enable a disabled stack")
            print("  disable <name>                      - Disable a stack")
            print("  start <name>                        - Start a stack's containers")
            print("  stop <name>                         - Stop a stack's containers")
            print("  logs <name> [-f]                    - Show stack logs")
            print("  info <name>                         - Show stack details")
            sys.exit(1)

        from .registry import handle_registry_command
        handle_registry_command(sys.argv[2:])

    elif command == "tui":
        from ..tui.app import main as tui_main
        tui_main()

    elif command == "uninstall":
        from .uninstall import cmd_uninstall
        cmd_uninstall()

    elif command == "docker":
        if len(sys.argv) < 3:
            print("Usage: infra docker <subcommand>")
            print("Subcommands:")
            print("  login    - Login to ghcr.io using gh auth")
            sys.exit(1)

        subcommand = sys.argv[2]

        if subcommand == "login":
            import subprocess

            # Get GitHub username
            user_result = subprocess.run(
                ["gh", "api", "user", "-q", ".login"],
                capture_output=True,
                text=True
            )
            if user_result.returncode != 0:
                print("✗ Failed to get GitHub username. Is gh auth configured?")
                sys.exit(1)

            username = user_result.stdout.strip()

            # Get token and login
            token_result = subprocess.run(
                ["gh", "auth", "token"],
                capture_output=True,
                text=True
            )
            if token_result.returncode != 0:
                print("✗ Failed to get gh auth token. Run 'gh auth login' first.")
                sys.exit(1)

            login_result = subprocess.run(
                ["docker", "login", "ghcr.io", "-u", username, "--password-stdin"],
                input=token_result.stdout,
                capture_output=True,
                text=True
            )
            if login_result.returncode == 0:
                print(f"✓ Logged in to ghcr.io as {username}")
            else:
                print(f"✗ Failed to login: {login_result.stderr}")
                sys.exit(1)
        else:
            print(f"Unknown docker subcommand: {subcommand}")
            sys.exit(1)

    elif command == "user":
        if len(sys.argv) < 3:
            print("Usage: infra user <subcommand>")
            print("Subcommands:")
            print("  delete <username>     - Delete a user")
            print("  delete -r <username>  - Delete a user and their home directory")
            sys.exit(1)

        subcommand = sys.argv[2]

        if subcommand == "delete":
            from ..core.users import UserManager

            # Check for -r flag
            remove_home = False
            username = None

            if len(sys.argv) < 4:
                print("Usage: infra user delete [-r] <username>")
                sys.exit(1)

            if sys.argv[3] == "-r":
                remove_home = True
                if len(sys.argv) < 5:
                    print("Usage: infra user delete -r <username>")
                    sys.exit(1)
                username = sys.argv[4]
            else:
                username = sys.argv[3]

            # Confirm deletion
            if remove_home:
                confirm = input(f"Delete user '{username}' AND their home directory? [y/N]: ")
            else:
                confirm = input(f"Delete user '{username}'? [y/N]: ")

            if confirm.lower() != 'y':
                print("Cancelled")
                sys.exit(0)

            result = UserManager.delete_user(username, remove_home)
            if result["success"]:
                print(f"✓ {result['message']}")
            else:
                print(f"✗ {result['message']}")
                sys.exit(1)
        else:
            print(f"Unknown user subcommand: {subcommand}")
            sys.exit(1)

    else:
        print(f"Unknown command: {command}")
        sys.exit(1)


if __name__ == "__main__":
    main()
