import typer

from grem.providers import GitServiceProvider

repo_app = typer.Typer()


def list_repos(ctx: typer.Context):
    """
    List all remote repositories.
    """
    provider: GitServiceProvider = ctx.obj.get('provider')

    for repo in provider.get_repos():
        typer.echo(repo.full_name)


def create_repos(ctx: typer.Context, names: tuple[str], private: bool = True):
    """
    Create new repositories.
    """

    provider: GitServiceProvider = ctx.obj.get('provider')

    for name in names:
        provider.create_repo(name, private=private)


def delete_repos(ctx: typer.Context, names: tuple[str], prefix: str | None = None):
    """
    Delete existing repositories.
    """

    provider: GitServiceProvider = ctx.obj.get('provider')

    for name in names:
        provider.delete_repo(name)

    if prefix is None or typer.prompt(f'Delete ALL repositories prefixed: {prefix}?', default='n').lower() == 'n':
        ctx.exit()

    for name in map(lambda repo: repo.full_name,
                    filter(lambda repo: repo.get_prefix() == prefix, provider.get_repos())):
        provider.delete_repo(name)


def archive_repos(ctx: typer.Context, names: list[str] = typer.Argument(..., help='Names of repositories to archive')):
    """
    Archive existing repositories.
    """

    provider: GitServiceProvider = ctx.obj.get('provider')

    for name in names:
        provider.archive_repo(name)
