from argparse import ArgumentParser
from pathlib import Path
from warnings import warn
from eggnog_mapper_fixurl.env import DOWNLOAD_EGGNOG_DATA_PYSCRIPT

def fixurl(download_eggnog_data_pyscript=DOWNLOAD_EGGNOG_DATA_PYSCRIPT):
    if not Path(download_eggnog_data_pyscript).is_file():
        warn(f'{download_eggnog_data_pyscript} does not seem to exist')
        return
    with open(download_eggnog_data_pyscript, 'r') as f:
        download_eggnog_data = f.read()
    if 'eggnogdb.embl.de' in download_eggnog_data:
        with open(download_eggnog_data_pyscript, 'w') as f:
            f.write(
                download_eggnog_data.replace(
                    'eggnogdb.embl.de',
                    'eggnog5.embl.de'
                )
            )


def parse_arguments():
    parser = ArgumentParser(description="fix outdated URLs in eggnog-mapper's download_eggnog_data.py")
    parser.add_argument(
        '--pyscript',
        default=DOWNLOAD_EGGNOG_DATA_PYSCRIPT,
        help=f'path to download_eggnog_data.py (default: {DOWNLOAD_EGGNOG_DATA_PYSCRIPT})'
    )
    return parser.parse_args()


def main():
    args = parse_arguments()
    fixurl(download_eggnog_data_pyscript=args.pyscript)
