import os
from nexus.nexus_api import delete_item, check_if_item_exists
from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary, write_github_summary, get_required_env_var


def prepare_params(repo, group, version, package_name) -> dict:
    params = {
        'version': version
    }
    if repo:
        params['repository'] = repo
    if group:
        params['group'] = group
    if package_name:
        params['name'] = package_name
    return params


def main():
    """
    Main function to check for the existence of a specific artifact in Nexus repository and remove it if found.

    The function retrieves the Nexus repository (`NEXUS_REPO`), group (`NEXUS_GROUP`), and package version (`PACKAGE_VERSION`)
    from the environment variables. It prepares the search parameters based on these values and checks if the artifact
    exists in the Nexus repository using the `check_if_item_exists` function. If the artifact exists and has a unique identifier,
    it is deleted using the `delete_item` function. If the artifact exists but no unique identifier is found (indicating multiple
    items found), an error summary is written. If the artifact does not exist, a log entry is made indicating nothing will be deleted.

    Environment Variables:
        NEXUS_REPO: The Nexus repository where the artifact is located. Defaults to 'npm-common'.
        NEXUS_GROUP: The group within the Nexus repository. Defaults to 'p81-common'.
        PACKAGE_VERSION: The version of the package to check and remove. This is a required variable.

    Raises:
        Exception: If `PACKAGE_VERSION` is not set in the environment variables, an error summary is written and the script exits.

    Notes:
        - The function logs information about the process, including whether the artifact was found and if it was deleted.
        - If an artifact is successfully deleted, a summary is written to GitHub indicating the package version removed.
    """
    repo = os.getenv('NEXUS_REPO', 'npm-common')
    group = os.getenv('NEXUS_GROUP', 'p81-common')
    version = get_required_env_var('PACKAGE_VERSION')
    package_name = os.getenv('PACKAGE_NAME')
    params = prepare_params(repo, group, version, package_name)
    is_exists, item_id = check_if_item_exists(params)
    if is_exists:
        logger.info(f"item {item_id} exists")
        if item_id:
            logger.info(f"item {item_id} exists and will be deleted")
            delete_item(item_id)
            write_github_summary(f"package {version} removed from nexus and will be pushed again later on")
        else:
            exit_on_error_and_write_summary(
                f"search for params {params} return True and empty item_id, probably multiple items found, cant delete them")
    else:
        logger.info(f"item not found for params {params}, nothing will be deleted")


if __name__ == '__main__':
    main()
