import json
import os

saru_home_ci = os.environ.get('SARU_HOME_CI')


class CIPayloadProcessor:
    def __init__(self):
        pass

    def process(self, payload):

        if 'saru' in payload:
            self.process_saru(payload)
        elif 'github' in payload:
            self.process_github(payload)

        return payload

    def process_saru(self, j):
        payload = json.loads(j)

        ref = self.get_saru_ref(payload)

        print(f"Processing Saru job {ref}...\n payload: {payload}")

    def process_github(self, j):
        payload = json.loads(j)
        ci_action_status = self.ataklibs_ci_action_status(payload)
        self.log_workflow_status(payload)

        if ci_action_status != "":
            status = ci_action_status[0]
            conclusion = ci_action_status[1]
            ref = ci_action_status[2]
            print(f"AtakLibs build status {status} for branch: {ref}...")
            if conclusion == "success":
                print("Successful AtakLibs build; running CI...")

                ## we don't have a great way of mapping the github ref to the saru job
                ## so lets just run the last job that we received from saru.
                ## I think eventually we can get a ci specfic ref in Saru e.g.  a branch named
                # ci_ref and build on that
                if ref != "":
                    self.run_saru_ci(ref)
                else:
                    print("No ref found; skipping CI run...")
        else:
            # print(f"No ref found for github payload... payload: {payload}")
            pass

    def run_saru_ci(self, ref):
        print(f"Running CI for ref: {ref}")
        os.system(f'cd {saru_home_ci} && glab ci run -b {ref}')

    def ataklibs_workflow_status(self, payload):
        try:
            if payload['workflow_job']['name'] == 'build-ataklibs':
                return payload['workflow_job']['status']
        except KeyError:
            return ""
        return ""

    def ataklibs_ci_action_status(self, payload):
        try:
            if payload['check_run']['name'] == 'build-ataklibs':
                status = payload['check_run']['status']
                conclusion = payload['check_run']['conclusion']
                head_branch = payload['check_run']["check_suite"]['head_branch']
                return status, conclusion, head_branch
        except KeyError:
            return ""
        return ""

    def get_saru_ref(self, payload):
        try:
            assert payload['object_attributes']['ref']
        except AssertionError:
            return ""
        return payload['object_attributes']['ref']

    def log_workflow_status(self, payload):
        workflow_status = self.ataklibs_workflow_status(payload)
        ref = self.get_github_ref(payload)
        if workflow_status != "":
            print(f"Workflow status: {workflow_status} for ref: {ref}")

    def get_github_ref(self, payload):
        try:
            assert payload['workflow_job']['head_branch']
        except KeyError:
            # print(f"No ref found in github payload {payload}")
            return ""
        return payload['workflow_job']['head_branch']
