#!/usr/bin/env python3

from termcolor_util import cyan, red, green, yellow
from typing import List, Any
import requests
import git_utils
import click
import os

RED_CIRCLE="🔴"
GREEN_CIRCLE="🟢"
YELLOW_CIRCLE="🟡"
WARNING_SIGN="⚠️"


class GitPr:
    def __init__(self, url: str, number: str) -> None:
        self.url = url
        self.number = number


class JenkinsBuildStatus:
    def __init__(self, last_build_url: str, status: str) -> None:
        self.last_build_url = last_build_url
        self.status = status


def find_git_pr(branch: str) -> GitPr:
    pr_number, pr_url = git_utils.get_github_pr(branch)
    return GitPr(url=pr_url, number=pr_number)

def find_jira_url(issue: str) -> str:
    jira_url = os.environ.get("JIRA_URL", "no JIRA URL in env ??")
    return f"{jira_url}/browse/{issue}"


def get_build_status(git_pr: GitPr) -> JenkinsBuildStatus:
    if not git_pr.url:
        return JenkinsBuildStatus("", "")

    jenkins_job = jenkins_fetch_job_data(git_pr)

    return JenkinsBuildStatus(
        status=jenkins_job["lastBuild"]["result"] if not jenkins_job["lastBuild"]["building"] else "BUILDING",
        last_build_url=jenkins_job["lastBuild"]["url"]
    )


def jenkins_fetch_job_data(git_pr: GitPr) -> Any:
    jenkins_prefix = os.getenv("JENKINS_PREFIX")
    jenkins_url = f"{jenkins_prefix}/view/change-requests/job/PR-{git_pr.number}/api/json?depth=1"
    r = requests.get(jenkins_url)
    return r.json()


def print_status(built_version: str,
                 git_pr: GitPr,
                 build_status: JenkinsBuildStatus) -> None:
    if not git_pr.url or not build_status.last_build_url:
        print(WARNING_SIGN + "  " + red(built_version, bold=True))
    elif build_status.status == "BUILDING":
        print(YELLOW_CIRCLE + " " + yellow(built_version, bold=True))
    elif build_status.status == "SUCCESS":
        print(GREEN_CIRCLE + " " + green(built_version, bold=True))
    else:
        print(RED_CIRCLE + " " + red(built_version, bold=True))

    print("   git    : " + cyan(git_pr.url))
    print("   jenkins: " + cyan(build_status.last_build_url))
    print()


@click.command()
@click.argument("issue", default="<from-branch>", nargs=1)
def main(issue: str) -> None:
    if issue == "<from-branch>":
        issue = git_utils.get_checkout_issue_number()

    built_versions = git_utils.find_branches_for_issue_id(issue)
    built_versions.sort()

    print(cyan(issue, bold=True))
    print(cyan('~' * len(issue), bold=True))
    print("jira: " + cyan(find_jira_url(issue)))
    print()

    for built_version in built_versions:
        git_pr = find_git_pr(built_version)
        build_status = get_build_status(git_pr)
        print_status(built_version, git_pr, build_status)


if __name__ == "__main__":
    main()

