import yaml
#import boto3
#import re
import os
import requests



def list_workflows(repo_name: str) -> dict:
    response = requests.get(
        f'{git_url}/{repo_name}/actions/workflows', headers=headers
    )
    if response.status_code == 200:
        res_json = response.json()
        return res_json
    else:
        print("no workflows found")
        return None


def find_right_workflow(workflow_name: str, workflows: dict) -> str:
    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']
                    return workflow_id
            else:
                print("no workflow with the name", workflow_name)
                return None


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


def find_latest_workflow_run_id(workflow_id: str, repo_name: str) -> str:
    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:
            # Sort the runs by the 'created_at' timestamp in descending order
            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("Error in getting workflow runs:")
        print(response.status_code)
        print(response.json())
        exit(1)
        return None


def get_run_link(latest_run_id: str, repo_name: str) -> str:
    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 print_workflow_link(workflow_id: str, repo_name: str) -> str:
    have_started = False
    latest_run_id = find_latest_workflow_run_id(workflow_id, repo_name)
    while not have_started:
        latest_latest_run_id = find_latest_workflow_run_id(workflow_id, repo_name)
        if latest_latest_run_id != latest_run_id:
            have_started = True
            latest_run_id = latest_latest_run_id
    run_url = get_run_link(latest_run_id, repo_name)
    print("link to the run: ", run_url)
    return run_url



git_token = os.getenv('GLOBAL_CICD_GIT_TOKEN')
git_url = "https://api.github.com/repos"
headers = {
    'Accept': 'application/vnd.github+json',
    'Authorization': f'Bearer {git_token}',
    'X-GitHub-Api-Version': '2022-11-28',
    'Content-Type': 'application/x-www-form-urlencoded',
}
file_path = "repos.yaml"
ecr_region = "us-east-1"
ecr_prefix = "corev3/"
workflow_name = "update_env_and_ecs"
# Read the YAML content from the file
with open(file_path, "r") as file:
    yaml_content = file.read()

# Parse the YAML content into Python objects
data = yaml.safe_load(yaml_content)

if isinstance(data, dict):
    ms_names = [service_data.get("ms_name") for service_data in data.values() if isinstance(service_data, dict)]
else:
    ms_names = []


ms_to_ignore = os.getenv('MS_TO_IGNORE').replace(" ", "").split(",")
if len(ms_to_ignore) > 1:
    for item in ms_to_ignore:   
        if item in ms_names:
            print(f"'{item}' exists in the dictionary.")
        else:
            print(f"'{item}' does not exist in the dictionary.")
            os.system(f'echo ":stop_sign: :rotating_light: {item} is not a valid micro_service" >> $GITHUB_STEP_SUMMARY')
            exit(1)

env_name = os.getenv("ENV_NAME")

for key, value in data.items():
    if isinstance(value, dict) and value.get("type") in ["backend", "core"]:
        ms_name = value.get("ms_name")
        latest_version = None
        if ms_name not in ms_to_ignore:
            ms_type = value.get("type")
            repo_name = f"perimeter-81/{key}"
            workflows = list_workflows(repo_name)
            workflow_id = find_right_workflow(workflow_name, workflows)
            if workflow_id:
                print(f"for repo {key} found {workflow_id}")
                run_workflow(workflow_id, "P81-30003-deploy-from-activitilog-to-padme", env_name, ms_type=ms_type, repo=repo_name)
                run_url =  print_workflow_link(workflow_id, repo_name)
                os.system(f'echo ":running_man:	 the deployment of the version: {latest_version} to env: solo is in [this workfkow]({run_url})" >> $GITHUB_STEP_SUMMARY')
            else:
                print(f"no workflows found for repo {key}")
                os.system(f'echo ":stop_sign: could not trigger workflow {repo_name} " >> $GITHUB_STEP_SUMMARY')

