#!/usr/bin/env python

purpose = '''
Convert Python script from BornAgain-21 to BornAgain-22.

Some conversions are too complicated to be automatized.
If unsupported constructs are encountered, this script will fail.

If a converted scripts still does not work under BornAgain-22,
then this is a bug, and should be reported to the maintainers.
'''

import os, re, sys

def replace_t(t):

    substitutions = {
        r'ba\.MultiLayer\(': 'ba.Sample(',
        r'setAngleDistribution\(': 'setGrazingAngleDistribution(',
        r'\n(\s*)bp.plot_simulation_result(\(.+?\))\s*\n': r'\n\1bp.plot_datafield\2\n\1bp.plt.show()\n',
        r'\n(\s*)bp.plot_multicurve_specular(\(.+?\))\s*\n': r'\n\1bp.plot_multicurve\2\n\1bp.plt.show()\n',
        r'\n(\s*)bp.make_plot(\(.+?\))\s*\n': r'\n\1bp.plot_to_grid\2\n\1bp.plt.show()\n',
        r'\n(\s*)bp.make_plot_row(\(.+?\))\s*\n': r'\n\1bp.plot_to_row\2\n\1bp.plt.show()\n',
        r'\n(\s*)bp.plot_histogram(\(.+?\))\s*\n+\s*[^\n]*?show_or_export\(\)\s*\n': r'\n\1bp.plot_datafield\2\n\1bp.plt.show()\n',
        r'\n\s*[^\n]*?parse_args\((.+?)\)\s*\n(.*bp.plot_(datafield|multicurve|to_grid|to_row)\(.*?)\)': r'\n\2, \1)',
    }
    for old, new in substitutions.items():
        t = re.sub(old, new, t, 0, re.DOTALL)

    prohibited = {
        r'plot_simulation_result',
        r'plot_multicurve_specular',
        r'show_or_export',
        r'parse_args',
        r'RectangularDetector',
        r'Roughness',
        r'RoughnessModel',
        r'CoreShell',
        r'Spheroid',
        r'Truncated',
        r'Coords_',
        r'setCrossCorrLength',
        r'bp\.datfield',
        r'result\.array',
        r'addSimulationAndData',
    }
    for old in prohibited:
        if len(re.findall(old, t)) > 0:
            raise Exception(f"Not able to convert '{old}'")

    return t

def main():
    if len(sys.argv) != 3:
        print(f"Usage: python {sys.argv[0]} <old_fname> <new_fname|new_dir>")
        print(purpose)
        sys.exit(1)

    old_fname, new_path = sys.argv[1], sys.argv[2]

    try:
        with open(old_fname, 'r', encoding='utf-8') as f:
            t = f.read()

        new_t = replace_t(t)

        if os.path.isdir(new_path):
            new_fname = os.path.join(new_path, os.path.basename(old_fname))
        else:
            new_fname = new_path

        with open(new_fname, 'w', encoding='utf-8') as f:
            f.write(new_t)

        # copy permissions
        os.chmod(new_fname, os.stat(old_fname).st_mode)

        if new_t == t:
            print(f"{os.path.basename(old_fname)}: OK (nothing changed). Output saved to {new_path}")
        else:
            print(f"{os.path.basename(old_fname)}: OK (substitutions done). Output saved to {new_path}")

    except FileNotFoundError:
        print(f"ERROR: The file '{old_fname}' does not exist.")
        sys.exit(1)
    except Exception as e:
        print(f"{os.path.basename(old_fname)}: ERROR: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
