# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import getpass
import re

import click

import releasetool.circleci
import releasetool.git
import releasetool.github
import releasetool.secrets
import releasetool.commands.common
from releasetool.commands.common import TagContext


def determine_release_pr(ctx: TagContext) -> None:
    click.secho(
        "> Let's figure out which pull request corresponds to your release.", fg="cyan"
    )

    pulls = ctx.github.list_pull_requests(ctx.upstream_repo, state="closed")
    pulls = [pull for pull in pulls if "release" in pull["title"].lower()][:30]

    click.secho("> Please pick one of the following PRs:\n")
    for n, pull in enumerate(pulls, 1):
        print(f"\t{n}: {pull['title']} ({pull['number']})")

    pull_idx = click.prompt("\nWhich one do you want to tag and release?", type=int)

    ctx.release_pr = pulls[pull_idx - 1]


def determine_release_tag(ctx: TagContext) -> None:
    click.secho("> Determining what the release tag should be.", fg="cyan")
    head_ref = ctx.release_pr["head"]["ref"]
    match = re.match(r"release-.+-(v\d+\.\d+\.\d+)", head_ref)

    if match is not None:
        ctx.release_tag = match.group(1)
    else:
        click.secho(
            "I couldn't determine what the release tag should be from the PR's"
            f"head ref {head_ref}.",
            fg="red",
        )
        ctx.release_tag = click.prompt(
            "What should the release tag be (for example, storage-1.2.3)?"
        )

    click.secho(f"Release tag is {ctx.release_tag}.")


def determine_package_name_and_version(ctx: TagContext) -> None:
    click.secho("> Determining the release version.", fg="cyan")
    match = re.match(r"v(\d+\.\d+\.\d+)", ctx.release_tag)
    ctx.release_version = match.group(1)
    click.secho(f"Package version: {ctx.release_version}.")


def get_release_notes(ctx: TagContext) -> None:
    click.secho("> Grabbing the release notes.", fg="cyan")

    match = re.search(
        r"This pull request was generated using releasetool\.\s+(.*)",
        ctx.release_pr["body"],
        re.DOTALL | re.MULTILINE,
    )
    if match is not None:
        ctx.release_notes = match.group(1).strip()
    else:
        ctx.release_notes = ""

    click.secho(f"Release notes:\n{ctx.release_notes}")


def create_release(ctx: TagContext) -> None:
    click.secho("> Creating the release.")

    ctx.github_release = ctx.github.create_release(
        repository=ctx.upstream_repo,
        tag_name=ctx.release_tag,
        target_committish=ctx.release_pr["merge_commit_sha"],
        name=ctx.release_tag,
        body=ctx.release_notes,
    )

    release_location_string = f"Release is at {ctx.github_release['html_url']}"
    click.secho(release_location_string)

    ctx.github.create_pull_request_comment(
        ctx.upstream_repo, ctx.release_pr["number"], release_location_string
    )


def tag() -> None:
    ctx = TagContext()

    click.secho(f"o/ Hey, {getpass.getuser()}, let's tag a release!", fg="magenta")

    releasetool.commands.common.setup_github_context(ctx)

    determine_release_pr(ctx)
    determine_release_tag(ctx)
    determine_package_name_and_version(ctx)

    # If the release already exists, don't do anything
    if releasetool.commands.common.release_exists(ctx):
        click.secho(f"{ctx.release_tag} already exists.", fg="magenta")
        return

    get_release_notes(ctx)
    create_release(ctx)

    click.secho(f"\\o/ All done!", fg="magenta")

@@ -3430,43 +3430,119 @@
 tag(
-) -%3E None:%0A    ctx = TagContext()%0A%0A
+ctx: TagContext = None) -%3E TagContext:%0A    if not ctx:%0A        ctx = TagContext()%0A%0A    if ctx.interactive:%0A    
     
@@ -3618,24 +3618,55 @@
 %22magenta%22)%0A%0A
+    if ctx.github is None:%0A    
     releaset
@@ -3708,24 +3708,59 @@
 ntext(ctx)%0A%0A
+    if ctx.release_pr is None:%0A    
     determin
@@ -3773,24 +3773,25 @@
 ase_pr(ctx)%0A
+%0A
     determin
@@ -4051,16 +4051,20 @@
   return
+ ctx
 %0A%0A    ge
@@ -4105,24 +4105,388 @@
 lease(ctx)%0A%0A
+    # Only enable release job triggering on google-auth-java-library for now.%0A    if ctx.upstream_repo == %22googleapis/google-auth-java-library%22:%0A        ctx.kokoro_job_name = (%0A            %22cloud-devrel/client-libraries/java/google-auth-java-library/release/stage%22%0A        )%0A        releasetool.commands.common.publish_via_kokoro(ctx)%0A%0A    if ctx.interactive:%0A    
     click.se
@@ -4506,24 +4506,40 @@
 l done!%22, fg=%22magenta%22)%0A
+%0A    return ctx%0A

Make releasetool tag trigger stage job for google-auth-java-library (#150)