import os
import sys
import requests
import time
from github.github_apis import create_git_headers

git_url = "https://api.github.com/repos"
headers = create_git_headers()

RECOMMENDED_WAIT_TIME_BEFORE_API_REQUEST = 20

def list_workflows(repo_name):
    response = requests.get(
        f'{git_url}/{repo_name}/actions/workflows', headers=headers
    )
    res_json = response.json()
    print("listed workflow")
    return res_json


def run_workflow(workflow_id, branch, inputs):
    data = {
    "ref": branch,
    "inputs": inputs
    }
    print(data)
    response = requests.post(
        f'{git_url}/{repo_name}/actions/workflows/{workflow_id}/dispatches',
        headers=headers, json=data)
    if response.status_code == 204:
        print("workflow run")
    else:
        print(f"error in running another workflow: for repo {repo_name} ")
        os.system(f'echo ":stop_sign: could not trigger the workflow for repo {repo_name} " >> $GITHUB_STEP_SUMMARY')
        print(response.status_code)
        print(response.json())
        exit(1)


def find_latest_workflow_run_id(workflow_id, repo_name):
    response = requests.get(f'{git_url}/{repo_name}/actions/workflows/{workflow_id}/runs', headers=headers)
    if response.status_code == 200:
        data = response.json()
        workflow_runs = data.get('workflow_runs', [])
        if workflow_runs:
            sorted_runs = sorted(workflow_runs, key=lambda x: x['created_at'], reverse=True)
            latest_run = sorted_runs[0]
            return latest_run['id']
        else:
            print("No workflow runs found.")
            return None
    else:
        print(f"Error in getting workflow runs: for repo {repo_name}")
        print(response.status_code)
        print(response.json())
        return None


def find_right_workflow(workflow_name, workflows):
    if workflows.get('workflows'):
        for workflow in workflows['workflows']:
            if workflow.get('path'):
                file_name = workflow['path'].replace('.github/workflows/', '').replace('.yaml', '').replace('.yml', '')
                if file_name == workflow_name:
                    workflow_id = workflow['id']
                    print("workflow id found")
                    return workflow_id



def get_run_link(latest_run_id):
    response = requests.get(f'{git_url}/{repo_name}/actions/runs/{latest_run_id}', headers=headers)
    if response.status_code == 200:
        data = response.json()
        print("workflow triggered successfully")
        return data["html_url"]
    else:
        print("Error in getting workflow run status:")
        print(response.status_code)
        print(response.json())
        return None


def handle_extra_args(extra_args_string):
    extra_args_dict = {}
    try:
        split_args = extra_args_string.split(",")
        for item in split_args:
            key, value = item.split("=")
            extra_args_dict[key.strip()] = value.strip()
    except Exception as e:
        print(f"error in handle extra args - {e}")
    return extra_args_dict

if __name__ == "__main__":
    workflow_name = sys.argv[1].replace("workflow_name=", "", 1)
    repo_name = sys.argv[2].replace("repo_name=", "", 1)
    branch = sys.argv[3].replace("branch=", "", 1)
    extra_args_string = sys.argv[4].replace("inputs=", "", 1)
    extra_args = handle_extra_args(extra_args_string)
    if repo_name == "":
        repo_name = os.getenv('GITHUB_REPOSITORY')
    if branch == '':
        branch = os.getenv('DEFAULT_BRANCH') or os.getenv('GITHUB_REF')
    print(f"branch name: {branch}")

    workflows = list_workflows(repo_name)
    workflow_id = find_right_workflow(workflow_name, workflows)
    if not workflow_id:
        print("did not find the right workflow id to run. exit")
        os.system(f'echo ":stop_sign: did not find the right workflow id to run. repo {repo_name} {workflow_name}" >> $GITHUB_STEP_SUMMARY')
        exit(1)

    run_workflow(workflow_id, branch, extra_args)
    # Get triggered workflow run id
    time.sleep(RECOMMENDED_WAIT_TIME_BEFORE_API_REQUEST) # Wait before getting for the new run id as Github API takes time to sync with last runs
    run_id = find_latest_workflow_run_id(workflow_id, repo_name)
    # Add run id as github output
    github_output = os.getenv("GITHUB_OUTPUT")
    if github_output:
        with open(github_output, "a") as f:
            f.write(f"RUN_ID={run_id}\n")



