import os
import argparse
from actions_logging.app_logging import logger
from github.env import exit_on_error_and_write_summary, write_github_env
import subprocess
from utils import download_file_from_nexus, add_nexus_arguments, get_nexus_base_url, compute_sha256, split_version


def run_lipo(path_x86, path_arm, output_path):
    try:
        path_to_create = output_path.split('firefly.dylib')[0]
        os.makedirs(f"{os.getcwd()}/{path_to_create}")
        commands = ["lipo", f"{path_x86}", f"{path_arm}", "-output", f"{output_path}", "-create"]
        result = subprocess.run(commands, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        logger.info_green(f"Lipo Output: {result.stdout}")
        logger.warning(f"Lipo Errors: {result.stderr}")
    except subprocess.CalledProcessError as e:
        exit_on_error_and_write_summary(f"An error occurred while unifiying the project: {e.stdout, e.stderr}")


def generate_download_urls(base_url, version, branch, gha_trigger, gha_run_number, arch):
    logger.info(f'branch: {branch}, gha_run_number: {gha_run_number}, gha_trigger: {gha_trigger}')
    major, minor, patch, build = split_version(version)
    file_path = f"macOS/{arch}/firefly.dylib"
    if gha_trigger == "release":
        return f"{base_url}/v{major}.{minor}/stable/{patch}/{build}/{file_path}"
    else:
        return f"{base_url}/{branch if branch == 'refs/heads/main' else 'v' + major+ '.'+ minor}/nightly/130{gha_run_number}/{file_path}"

if __name__ == "__main__":
    # Parse command-line arguments
    parser = argparse.ArgumentParser(description="Get input parameters")
    add_nexus_arguments(parser)
    parser.add_argument('--nexus_user', type=str, nargs='?', help='Nexus username')
    parser.add_argument('--nexus_password', type=str, nargs='?', help='Nexus password')
    parser.add_argument('--version', type=str, nargs='?', help='Latest version of stable build')
    parser.add_argument('--branch', type=str, nargs='?', help='Branch name')
    parser.add_argument('--gha_trigger', type=str, nargs='?', help='Trigger for GH action')
    parser.add_argument('--gha_run_number', type=str, nargs='?', help='Run number for GH action')

    args = parser.parse_args()
    base_url = get_nexus_base_url(args)
    for arch in ["ARM64", "X64"]:
        url = generate_download_urls(base_url, args.version, args.branch, args.gha_trigger,
                                     args.gha_run_number, arch)
        download_file_from_nexus(args.nexus_user, args.nexus_password, url, f"build/{arch}", False, "")
    run_lipo(f"build/ARM64/firefly.dylib", f"build/X64/firefly.dylib", f"build/unified/firefly.dylib")
    hash = compute_sha256("build/unified/firefly.dylib")
    if hash is None or hash == "":
        exit_on_error_and_write_summary(f"Failed to compute hash for unified firefly.dylib")
    write_github_env(hash, "HASH")
