#!/usr/bin/env python3
"""Updates version.yml and CHANGELOG.md for next version, then
launch the `git citool` GUI to create a commit of it.
"""

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.start_release_updates import update_versions_yaml, update_changelog_date


HOTFIX_MESSAGE = """
All commits that are going out in {next_ver} release **must** be on {hotfix_branch}.
This will allow the appropriate CI to run.

To get the hotfix changes onto this branch you can do one of the following:
    * use {hotfix_branch} as the development branch for the fix
    * land (or have already landed) hotfix changes on {release_train} branch, and merge {release_train} into {hotfix_branch}
    * cherry-pick hotfix commits from ambassador.git to {hotfix_branch}

It is okay if you've already landed the hotfix changes on {release_train} branch,
reviewers just need to validate that the hotfix commits are in the tree for {hotfix_branch},
and all the appropriate changelog updates exist.

## REVIEWERS MUST CHECK THAT:
* hotfix commits are on {hotfix_branch}
* CHANGELOG updates are on {hotfix_branch}
"""


def main(next_ver: str, today: datetime.date, quiet: bool=False, commit: bool = True) -> int:
    """This edits several files (the Git directory "tree"), then launches
    the `git citool` GUI to commit them.  This _should_ be an utterly
    trivial and readable list of
        for line in fileinput.FileInput("FILENAME", inplace=True):
            # edit 'line' as appropriate
            sys.stdout.write(line)
        git_add("FILENAME")
    blocks.  However, the block to edit the CHANGELOG.md file is unfortunately a
    touch more complex, because it has to deal with parsing the file in to
    sections and buffering the sections... maybe line-oriented processing wasn't
    the best choice for that file.
    """
    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"])

    if not quiet:
        print()
        print(f'Doing basic updates for v{next_ver}...')
        print()

    # 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)
    assert m
    release_branch = f"release/v{m[vX]}.{m[vY]}"
    with check(f"Checking that {release_branch} exists"):
        run(["git", "fetch"])
        run(["git", "rev-parse", "--verify", f"{release_branch}"])
    if not checker.ok:
        print(f"{release_branch} doesn't exist and you're doing a hotfix")
        print("Please create it, then rerun")
        return 1
    current_release_branch = f"rel/v{next_ver}"
    with check(f"Checking if {current_release_branch} exists (Don't worry if this step fails)"):
        run(["git", "rev-parse", "--verify", f"{current_release_branch}"])
    if checker.ok:
        with check(f"Checking out {current_release_branch} and making it up to date with {release_branch}"):
            run(["git", "checkout", current_release_branch])
            run(["git", "pull", "origin", current_release_branch])
            run(["git", "merge", f"origin/{release_branch}"])
        if not checker.ok:
            return 1
        with check(f"Checking if there are conflicts in merge"):
            out = run_capture(["git", "status", "--porcelain"])
            if out:
                raise AssertionError(f"Merge conflicts on {current_release_branch}. Resolve these, then rerun this scrip")
        if not checker.ok:
            return 1
    else:
        checker.ok = True
        with check(f"Creating {current_release_branch} (IGNORE PREVIOUS STEP FAILURE)"):
            run(["git", "checkout", f"origin/{release_branch}", "-b", current_release_branch])
            run(["git", "push", "-u", "origin", current_release_branch])
        if not checker.ok:
            print(f"Could not create {current_release_branch}.")
            print("Please fix issues then rerun")
            return 1
    with check(f"Updating docs/yaml/versions.yml with {next_ver}..."):
        update_versions_yaml(next_ver)

    with check(f"Updating CHANGELOG.md with {next_ver}..."):
        update_changelog_date(next_ver)

    if checker.ok and commit:
        with check(f"Committing changes..."):
            gitdir = run_capture(['git', 'rev-parse', '--git-dir'])
            with open(os.path.join(gitdir, 'GITGUI_MSG'), 'w') as msgfile:
                msgfile.write(f"Update for v{next_ver}\n")
            if getenv("AMBASSADOR_RELENG_NO_GUI"):
                run(['git', 'commit', '-am', f'Update for v{next_ver}'])
            else:
                run(['git', 'citool'])
        if not checker.ok:
            return 1
        run(["git", "push", "-u", "origin", current_release_branch])
        with check(f"Creating PR for {current_release_branch}"):
            run(["gh", "pr", "create",
                    "--repo", get_gh_repo(),
                    "--base", release_branch,
                    "--title", f"[v{next_ver}] Release Branch",
                    "--body", HOTFIX_MESSAGE.format(next_ver=next_ver, hotfix_branch=current_release_branch, release_train=release_branch),
                    "--reviewer", "kflynn,rhs,esmet,acookin"])

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


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,
    ))
