from actions_logging.app_logging import logger
import argparse
from github.env import exit_on_error_and_write_summary, write_github_env
from time import sleep
import requests
from requests.auth import HTTPBasicAuth
from utils import download_file_from_nexus, compute_sha256
import os

max_wait_time = 60 * 15


def file_exists_in_nexus(nexus_url, repo_name, file_path, username, password):
    url = f"https://{nexus_url}/repository/{repo_name}/{file_path}"
    try:
        response = requests.head(url, auth=HTTPBasicAuth(username, password))
        return response.status_code == 200

    except requests.RequestException as e:
        exit_on_error_and_write_summary(f"Error checking file existence: {e}")
        return False


def delete_file_from_nexus(nexus_url, repo_name, file_path, username, password):
    url = f"https://{nexus_url}/repository/{repo_name}/{file_path}"
    print(url)

    response = requests.delete(url, auth=HTTPBasicAuth(username, password))

    if response.status_code == 204:
        logger.info(f"File {url} deleted successfully.")
    elif response.status_code == 404:
        exit_on_error_and_write_summary(f"File {url} not found.")
    else:
        exit_on_error_and_write_summary(f"Failed to delete file: {response.status_code} - {response.text}")
    return response


def await_file_signing(nexus_url, repo_name, file_path, username, password):
    elapsed_time = 0
    while not file_exists_in_nexus(nexus_url, repo_name, file_path, username, password):
        if elapsed_time >= max_wait_time:
            exit_on_error_and_write_summary(
                f"File {file_path} not found in Nexus repository after {max_wait_time} seconds.")
        logger.info("Signed file not found yet, Sleeping for 15 Seconds")
        sleep(15)
        elapsed_time += 15
    logger.info(f"File {file_path} found in Nexus repository after {elapsed_time} seconds.")
    return True


if __name__ == "__main__":
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description="Get input parameters")
    parser.add_argument('--nexus_url', type=str, nargs='?', help='Nexus repository URL')
    parser.add_argument('--file_path', type=str, nargs='?', help='Path to file for upload')
    parser.add_argument('--repository', type=str, nargs='?', help='Nexus repository name')
    parser.add_argument('--target_path', type=str, nargs='?', help='Target path in Nexus repository')
    parser.add_argument('--nexus_username', type=str, nargs='?', help='Nexus username')
    parser.add_argument('--nexus_password', type=str, nargs='?', help='Nexus password')

    args = parser.parse_args()

    await_file_signing(args.nexus_url, args.repository, args.target_path, args.nexus_username, args.nexus_password)
    url = f"https://{args.nexus_url}/repository/{args.repository}/{args.target_path}"
    download_file_from_nexus(args.nexus_username, args.nexus_password, url, args.file_path, False, "")
    delete_file_from_nexus(args.nexus_url, args.repository, args.target_path, args.nexus_username, args.nexus_password)
    delete_file_from_nexus(args.nexus_url, args.repository, f"{args.target_path}".replace("signed", "unsigned"),
                           args.nexus_username, args.nexus_password)

    file_name = os.path.basename(url)
    destination = os.path.join(args.file_path, file_name)
    logger.info(f"File downloaded to {destination}")
    hash = compute_sha256(destination)
    if hash is None or hash == "":
        exit_on_error_and_write_summary(f"Failed to compute hash for {args.file_path}")
    write_github_env(hash, "HASH")
