import git
import os
import shlex
import subprocess

from urllib.parse import urlparse

from app.utils import op_dev_service


CLONE_REPOSITORY_SH = """
set -e
cd %(dest_dir)s
git init
git config --local op-dev.pkg-id '%(pkg_id)s'
git config --local user.name %(name)s
git config --local user.email %(email)s
git config --local credential.helper ''
git config --local --add credential.helper '!op-dev credential-helper --team-id %(team_id)s $@'
git config --local credential.UseHttpPath 'true'
git remote add origin %(repository_url)s
git fetch
git pull origin main
git push --set-upstream origin main
"""

def clone_repository(name, email, repository_url, team_id, pkg_id, dest_dir):
  """
  Clones the repository from the remote URL and initializes to be used with the specified AWS profile. Fails
  if the 'dest_dir' already exists or the AWS profile is invalid.
  """
  os.makedirs(dest_dir)
  cmd = CLONE_REPOSITORY_SH % {
    "pkg_id": pkg_id,
    "dest_dir": shlex.quote(dest_dir),
    "name": shlex.quote(name),
    "email": shlex.quote(email),
    "repository_url": shlex.quote(repository_url),
    "team_id": team_id
  }
  subprocess.check_output(cmd, shell=True)


def run(parser, args):
  user = op_dev_service.call('get-user', None)
  if args.team:
    team = args.team
    team_id = op_dev_service.call('find-team', { 'name': team })
  else:
    teams = op_dev_service.call('list-teams', None)
    if len(teams) > 1:
      parser.error('--team is required when you are a member of multiple teams')
    else:
      team_id = teams[0][0]
  pkg_id, pkg = op_dev_service.call('find-package', { 'team_id': team_id, 'name': args.pkg })

  clone_repository(user['name'], user['email'], pkg['repository_url'], team_id, pkg_id, args.pkg)

  print('Package successfully cloned')
