#!/usr/bin/env python3
"""Merges master into the release branch, then PRs back to master
"""

from os import getenv
import datetime
import fileinput
import os.path
import re
import sys
from contextlib import contextmanager
from typing import Generator
from shutil import which

from lib import base_version, build_version, git_add, git_check_clean, re_ga, vX, vY, get_gh_repo
from lib.uiutil import Checker, CheckResult, run
from lib.uiutil import run_txtcapture as run_capture
from lib import ansiterm

DEFAULT_REPO = 'git@github.com:emissary-ingress/emissary'


def main(next_ver: str, today: datetime.date, quiet: bool=False, commit: bool = True) -> int:
    if which("gh") is None:
        print("gh tool is not installed.")
        print("Please install the tool and rerun this script:")
        print("https://github.com/cli/cli#installation")
        return 1

    if not getenv("GITHUB_TOKEN"):
        run(["gh", "auth", "login"])

    warning = """
 ==> Warning: FIXME: This script does not have the property that if
     something goes wrong, you can just restart it; put another way:
     it does not have the property that each step is idempotent.
     If something does go wrong, then you'll have to address it, then
     resume where the script left off by going through the checklist
     manually (or by commenting out the already-completed steps).
"""
    print(f"{ansiterm.sgr.fg_red}{warning}{ansiterm.sgr}")

    # This context manager and check function are pretty much just to produce
    # a nice list of steps...
    checker = Checker()

    @contextmanager
    def check(name: str) -> Generator[CheckResult, None, None]:
        with checker.check(name) as subcheck:
            # time.sleep(1)  # it's stupid, but honestly the delay makes the output more readable
            yield subcheck

    m = re_ga.match(next_ver)
    release_branch = f"release/v{m[vX]}.{m[vY]}"
    with check("You're in a clean checkout"):
        git_check_clean()
    with check(f"You're on {release_branch}"):
        cur_branch = run_capture(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])

        if (cur_branch != release_branch):
            raise AssertionError(f"You repatriate from from {cur_branch}")
    if not checker.ok:
        return 1
    remote_repo = getenv('AMBASSADOR_RELEASE_REPO_OVERRIDE')
    if remote_repo is None or remote_repo == '':
        remote_repo = DEFAULT_REPO
    with check("You're up-to-date with ambassador.git"):
        remote_name = f'{remote_repo}.git'

        branch_up_to_date(
            remote=remote_name,
            branch=cur_branch,
            update_cmd=f'git pull {remote_name} {cur_branch}',
        )
    if not checker.ok:
        return 1

    repatriate_branch = getenv("USER") + f"/repatriate/{next_ver}"
    with check(f"Creating repatriation branch {repatriate_branch}"):
        run(["git", "checkout", "-b", repatriate_branch])
    if not checker.ok:
        return 1
    with check(f"Merging master into {repatriate_branch}"):
        run(["git", "merge", "origin/master"])
    with check(f"Checking if there was a clean merge"):
        out = run_capture(["git", "status", "--porcelain"])
        if out:
            raise AssertionError(f"Merge conflicts on {repatriate_branch}. Resolve these, then run 'gh pr create --base {release_branch}' to create a PR")
    if not checker.ok:
        return 1

    with check(f"Pushing changes to {repatriate_branch}"):
        run(["git", "push", "-u", "origin", repatriate_branch])

    if not checker.ok:
        return 1
    with check(f"Creating PR for {repatriate_branch}"):
        run(["gh", "pr", "create",
                "--repo", get_gh_repo(),
                "--title", f"[v{next_ver}] Repatriation",
                "--body", f"Repatriate changes from releasing {next_ver}",
                "--reviewer", "kflynn,rhs,esmet,acookin"])

    if checker.ok:
        if getenv("AMBASSADOR_RELENG_NO_GUI"):
            run(["gh", "pr", "view", repatriate_branch, "--repo", get_gh_repo()])
        else:
            run(["gh", "pr", "view", repatriate_branch, "--repo", get_gh_repo(), "--web"])
        return 0
    else:
        return 1


def branch_up_to_date(remote: str, branch: str, update_cmd: str) -> None:
    run(['git', 'fetch', remote, f'refs/heads/{branch}'])
    try:
        run(['git', 'merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])
    except Exception as err:
        print(f"HEAD is not up-to-date with '{remote}' '{branch}':")
        print("You need to update it with:")
        print()
        print(f"    $ {update_cmd}")
        print()
        raise


if __name__ == '__main__':
    args = sys.argv[1:]

    quiet = False
    commit = True

    while args and args[0].startswith("--"):
        if args[0] == '--quiet':
            quiet = True
            args.pop(0)
        elif args and (args[0] == '--no-commit'):
            commit = False
            args.pop(0)

    if len(args) != 1 or not re_ga.match(args[0]):
        sys.stderr.write(f"Usage: {os.path.basename(sys.argv[0])} X.Y.Z\n")
        sys.exit(2)

    sys.exit(main(
        next_ver=args[0],
        today=datetime.date.today(),
        quiet=quiet,
        commit=commit,
    ))
