#!/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
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, 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


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
    orig_branch = run_capture(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])

    user = getenv("USER")
    if user is None or user == '':
        user = 'unknownuser'
    workbranch = f"{user}/v{next_ver}/start-release"
    with check(f"Checking out branch {workbranch}"):
        run(["git", "checkout", "-b", workbranch])
    if not checker.ok:
        return 1

    # docs/yaml/versions.yml
    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'])
            run(["git", "push", "-u", "origin", workbranch])
        if not checker.ok:
            return 1
        with check(f"Creating PR for {workbranch}"):
            run(["gh", "pr", "create",
                    "--repo", get_gh_repo(),
                    "--base", orig_branch,
                    "--title", f"[v{next_ver}] Prep work for next scheduled release",
                    "--body", f"Updates for next version {next_ver}",
                    "--reviewer", "kflynn,rhs,esmet,acookin"])

    if checker.ok:
        print(f'Update complete. Merge PR back to target branch ASAP')
        if getenv("AMBASSADOR_RELENG_NO_GUI"):
            run(["gh", "pr", "view", workbranch, "--repo", get_gh_repo()])
        else:
            run(["gh", "pr", "view", workbranch, "--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,
    ))
