from actions_logging.app_logging import logger
import argparse
from github.env import exit_on_error_and_write_summary
# from nexus_download import download_file
from time import sleep
import requests
from requests.auth import HTTPBasicAuth
import os, io
import zipfile

max_wait_time = 60*15

def download_file_from_nexus(url, destination_directory, unzip, username, password):
    logger.info(f"Downloading file: url:{url}, destination_directory:{destination_directory}, unzip:{unzip}")
    if not os.path.exists(destination_directory):
        os.makedirs(destination_directory)
        print(f"Directory {destination_directory} created.")

    file_name = os.path.basename(url)
    destination = os.path.join(destination_directory, file_name)

    response = requests.get(url, auth=(username, password))
    logger.info(f"Download status code: {response.status_code}")
    response.raise_for_status()

    logger.info(f'File {file_name} downloaded successfully')

    if unzip:
        with zipfile.ZipFile(io.BytesIO(response.content)) as z:
            z.extractall(destination_directory)
        print(f'File {file_name} unzipped successfully to {destination_directory}')
    else:
        with open(f'{destination}', 'wb') as f:
            f.write(response.content)


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_dir', type=str, nargs='?', help='Target directory 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_dir, args.nexus_username, args.nexus_password)
    url = f"https://{args.nexus_url}/repository/{args.repository}/{args.target_dir}"
    download_file_from_nexus(url, args.file_path, False,  args.nexus_username, args.nexus_password)
    delete_file_from_nexus(args.nexus_url, args.repository, args.target_dir, args.nexus_username, args.nexus_password)
    delete_file_from_nexus(args.nexus_url, args.repository, f"{args.target_dir}".replace("signed", "unsigned"), args.nexus_username, args.nexus_password)
