import os
import subprocess
from .branch import branch_details
from utils.format import format_branch
from utils.git_commands import (
    git_add_worktree,
    git_remove_worktree,
)
from utils.messages import (
    title,
    instructions,
    worktree_instructions,
)


def add_worktree(worktree=None, auto_install=False):

    # Check for bare repo
    try:
        with open('config') as git_config:
            content = ' '.join(git_config.readlines())
            if 'bare = true' in content:

                # Ask for worktree folder name

                if worktree is None:
                    title('Create Worktree')
                    instructions(worktree_instructions)
                    worktree = input('Worktree Directory Name: ')

                # Get branch details
                branch_type, branch_id = branch_details()

                # Format branch name
                branch_name = format_branch(
                    branch_type,
                    branch_id,
                    worktree,
                )

                # Create worktree
                git_add_worktree(worktree, branch_name)

                # Install NPM packages after worktree creation
                if auto_install:
                    os.chdir(f"./{worktree}")

                    subprocess.run(['/bin/bash', '-i', '-c', 'nvm use'])
                    subprocess.run(['npm', 'i'])

                exit(0)

    except Exception:
        print('No worktree found')
        exit(1)


def remove_worktree(worktree):
    worktree_name = worktree if worktree else input('Worktree to remove: ')
    git_remove_worktree(worktree_name)
