#!/usr/bin/env python3
# SPDX-FileCopyrightText: (C) 2022 Avnet Embedded GmbH
# SPDX-License-Identifier: GPL-3.0-only

# Check if we can safely shutdown the self-hosted-runner

import argparse
import logging
import requests
from requests.adapters import HTTPAdapter, Retry
import os

RUN_STATUS = ['null', 'in_progress', 'pending',
              'queued', 'requested', 'waiting']


logging.getLogger().setLevel(logging.INFO)


class ApiException(Exception):
    """Class to proxy errors from GitHub's API"""

    pass


class GithubClient():
    """Class to handle connection to Azure API"""

    def __init__(self):
        """Class Constructor"""
        self.headers = {
            "content_type": "application/json",
            "authorization": f"bearer {os.getenv('GITHUB_PAT')}",
        }
        self.session = requests.Session()
        retries = Retry(
            total=5,
            backoff_factor=1,
            status_forcelist=[429, 500, 502, 503, 504],
        )
        self.session.mount('https://', HTTPAdapter(max_retries=retries))

    def get_workflow_runs(self) -> list[dict]:
        """Get all the runs for our job_build workflow."""
        request = self.session.get(
            "https://api.github.com/repos/avnet-embedded/simplecore-tools/actions/workflows/job_build.yml/runs?per_page=100",
            headers=self.headers,
        )
        if request.status_code == 401:
            logging.error("Wrong or missing token")
            raise ApiException()
        elif request.status_code != 200:
            logging.error(f"Request error {request.status_code}")
            return []
        runs = request.json()
        return runs.get('workflow_runs', [])


def get_args() -> argparse.Namespace:
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        prog="shutdown-check",
        description="Checks if we can shutdown the VMs",
    )

    return parser.parse_args()


def main():
    """Main function"""
    try:
        client = GithubClient()
        for run in client.get_workflow_runs():
            logging.info(f'run {run.get("id")} -> {run.get("status", "")}')
            if run.get('status', 'null') in RUN_STATUS:
                # Skip on our own run
                if os.environ.get('GITHUB_RUN_ID', '') == str(run.get('id', '')):
                    continue

                logging.info(
                    'Found active item in queue for this runner - no shutdown')
                return -1

    except ApiException:
        return -2

    except Exception as e:
        logging.exception(e)

    logging.info('No active job found - shuting down')
    return 0


if __name__ == "__main__":
    exit(main())
