#!/usr/bin/env python3
from gitz import git_functions
from gitz.env import ENV
from gitz.program import PROGRAM
from gitz.program import safe_git
from gitz.program import git

SUMMARY = 'Create and push fresh branches from a reference branch'
USAGE = 'git fresh <branch-name> [...<branch-name>]'
HELP = """
Create a branch, fetch the upstream remote, get the commit ID
of the tip of the reference branch (by default, either develop or master)
and push to the origin
"""
EXAMPLES = """
git fresh foo
   Create a new branch foo and push to the origin

git fresh one two three
   Create three new branches
"""


_HELP_BRANCHES = 'Names of branches to create'


def git_fresh():
    git_functions.check_clean_workspace()
    branches = PROGRAM.args.branches
    for branch in branches:
        _run_fresh(branch)

    message = 'New branch' if len(branches) == 1 else 'New branches'
    PROGRAM.log.message(message, ','.join(branches))


def _run_fresh(fresh_branch):
    branches = git_functions.branches()
    if fresh_branch in branches:
        PROGRAM.error('Branch name', fresh_branch, 'already exists')

    remotes = safe_git.remote()
    if len(remotes) == 1:
        origin = upstream = remotes[0]
    else:
        origin = ENV.origin()[0]
        if origin not in remotes:
            PROGRAM.error('Unknown origin', origin)

        upstream = next((u for u in ENV.upstream() if u in remotes), None)
        if upstream is None:
            PROGRAM.error('No upstream found')

    if PROGRAM.called.get('error'):
        PROGRAM.exit()

    safe_git.fetch(upstream)

    for branch in ENV.reference_branches():
        refspec = '%s/%s' % (upstream, branch)
        if git_functions.commit_id(refspec):
            git.checkout('-b', fresh_branch, refspec, quiet=True)
            git.push('-u', origin, fresh_branch, quiet=True)
            PROGRAM.message('Created fresh branch', fresh_branch)
            return

    PROGRAM.exit('No reference branch found')


def add_arguments(parser):
    parser.add_argument('branches', nargs='+', help=_HELP_BRANCHES)


if __name__ == '__main__':
    PROGRAM.start(**globals())
