import os
import json
from actions_logging.app_logging import logger
from common.common import run_command
from aws.constants import STG_PROD_ENVS
from common.common import run_command
from git.constants import IS_HOTFIX
from git.utils import get_commit_hash, tag_and_push
from github.env import exit_on_error_and_write_summary, get_required_env_var, write_github_env


def merge_jsons(first_json_path, second_json_path, output_path=""):
    with open(first_json_path, 'r') as old_file:
        firs_data = json.load(old_file)

    with open(second_json_path, 'r') as lambda_file:
        second_data = json.load(lambda_file)

    merged_data = deep_merge(firs_data, second_data)

    if output_path:
        # Save the merged result into the package.json file
        with open(output_path, 'w') as output_file:
            json.dump(merged_data, output_file, indent=2)
            logger.info(f"Successfully merged into {output_path}")

    return merged_data


def deep_merge(dict1, dict2):
    for key in dict2:
        if key in dict1 and isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
            deep_merge(dict1[key], dict2[key])
        else:
            dict1[key] = dict2[key]
    return dict1

def update_version_in_package_json_file(new_version, file_path = 'package.json'):
    # Read the existing package.json file
    with open(file_path, 'r') as file:
        package_data = json.load(file)

    # Update the version
    if 'version' in package_data:
        package_data['version'] = new_version
    else:
        raise KeyError("No 'version' field found in the package.json file")

    # Write the updated package.json file
    with open(file_path, 'w') as file:
        json.dump(package_data, file, indent=2)

    logger.info(f'Updated version to {new_version} in {file_path}')


def main():
    try:
        env_name = get_required_env_var('ENV_NAME')
        build_num = get_required_env_var('GITHUB_RUN_NUMBER')
        commit_sha = get_commit_hash()
        hotfix_version_prefix = f'0.0.0-'
        dev_version = f'{env_name}-{build_num}-{commit_sha}'
        is_hotfix_case = env_name in STG_PROD_ENVS
        is_multiservice_repo = os.getenv("IS_MULTI_SERVICE_REPO", 'false') == 'true'
        lambda_path = os.getenv('MS_PATH', os.getcwd())
        old_json_path = 'old.json'
        lambda_package_json_path = f"{lambda_path}/package.json"
        output_json_path = 'package.json'

        if not is_multiservice_repo:
            logger.info(f'IS_MULTI_SERVICE_REPO var is not equal to true. Will continue as a mono service repo')
        else:
            logger.info(f'Is multi service repo: {is_multiservice_repo}')
            os.rename('package.json', old_json_path)
            merge_jsons(old_json_path, lambda_package_json_path, output_json_path)
        run_command('npm run build:lambda')
        logger.info_green('build succeed')
        if is_hotfix_case:
            hotfix_version = f'{hotfix_version_prefix}{dev_version}'
            logger.info(f'Updating package json file with hotfix version: {hotfix_version}')
            update_version_in_package_json_file(hotfix_version, output_json_path)
            logger.info('Publishing hotfix to nexus.')
            run_command('npm publish --verbose')
            tag_and_push(dev_version)
        write_github_env(dev_version, 'DEPLOYED_ARTIFACT_VERSION')
    except Exception as e:
        exit_on_error_and_write_summary(f'Error package_build.py. Reason: {e}')


if __name__ == "__main__":
    main()
