import base64
import requests
from actions_logging.app_logging import logger
import argparse
from github.env import exit_on_error_and_write_summary


def upload_to_nexus(file_path, nexus_url, repository, target_dir, nexus_user, nexus_password):
    upload_url = f"https://{nexus_url}/service/rest/v1/components?repository={repository}"
    logger.info(f"Uploading {file_path}  to {target_dir}")

    file_name = target_dir.split("/")[-1]
    target_dir = target_dir.replace(file_name, "")
    files = {
        'raw.directory': (None, target_dir),
        'raw.asset1': (file_name, open(file_path, 'rb')),
        'raw.asset1.filename': (None, file_name)
    }

    auth = base64.b64encode(f"{nexus_user}:{nexus_password}".encode()).decode()
    headers = {
        'accept': 'application/json',
        'Authorization': f'Basic {auth}'
    }

    logger.info(f"Uploading {file_path}  to {target_dir}")
    response = requests.post(upload_url, files=files, headers=headers)
    logger.info(f"Response: {response.status_code}")
    logger.info(f"Response Text: {response.text}")
    if response.status_code >= 300:
        exit_on_error_and_write_summary(f"Failed to upload {file_path} to Nexus repository, got response code {response.status_code}")
    return response

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_user', type=str, nargs='?', help='Nexus username')
    parser.add_argument('--nexus_password', type=str, nargs='?', help='Nexus password')
    args = parser.parse_args()
    logger.info(args.target_dir)
    upload_to_nexus(args.file_path, args.nexus_url, args.repository, args.target_dir, args.nexus_user, args.nexus_password)