#!/usr/bin/env python3
import os
import subprocess

import click
from dotenv import load_dotenv

load_dotenv()


def get_current_branch():
    """Get the current git branch name."""
    try:
        branch = (
            subprocess.check_output(
                ["git", "rev-parse", "--abbrev-ref", "HEAD"],
                stderr=subprocess.DEVNULL,
            )
            .decode()
            .strip()
        )
        return branch
    except subprocess.CalledProcessError:
        return "main"  # fallback


@click.command()
@click.option(
    "-b",
    default=lambda: get_current_branch(),
    show_default="current branch",
    help="The branch or tag name to push, default is current branch",
)
@click.argument("git_args", nargs=-1, type=click.UNPROCESSED)  # receive other args
def push(b, git_args):
    git_push_cmd = ["git", "push", "-u", "origin", b]
    git_push_cmd.extend(git_args)
    git_push_cmd_str = " ".join(git_push_cmd)

    os.system(f"""/usr/bin/expect <<EOF
    set timeout 10
    spawn {git_push_cmd_str}
    expect "Username for"
    send "$REPO_USERNAME\r"
    expect "Password for"
    send "$REPO_TOKEN\r"
    expect eof
EOF""")


if __name__ == "__main__":
    push()
