import argparse
from pathlib import Path
import shutil

parser = argparse.ArgumentParser(description='Add XSLT-polyfill to Numbas packages')

parser.add_argument('path', help='The directory to scan for exam packages')
parser.add_argument('--script-url', help='URL to the XSLT-polyfill script. If not given, the script is copied into each package separately.')
parser.add_argument('--script-path', default='xslt-polyfill.min.js', help='Local path of the XSLT-polyfill script.')
parser.add_argument('--write', action='store_true', help='Print the path of each package that would be modified, but don\'t actually change anything.')

args = parser.parse_args()

polyfill_script_name = 'xslt-polyfill.min.js'

try:
    script_path = Path(args.script_path)

    if args.script_url is None and not script_path.exists():
        raise Exception(f"Give a URL for the XSLT-polyfill script with the --script-url option, or a local path to the file with the --script-path option.")

    root = Path(args.path)
    
    num_fixed = 0

    for d, ds, fs in root.walk():
        if 'numbas-manifest.json' not in fs or 'index.html' not in fs:
            continue

        if args.script_url is None:
            shutil.copyfile(script_path, d / polyfill_script_name)
            url = polyfill_script_name
        else:
            url = args.script_url

        index_path = d / 'index.html'

        with open(index_path) as f:
            index_html = f.read()

        if 'xslt-polyfill' in index_html:
            continue

        print(d)
        if not args.write:
            continue

        index_html = index_html.replace('</head>', f'    <script src="{url}"></script>\n</head>')
        with open(index_path, 'w') as f:
            f.write(index_html)

        num_fixed += 1

    if not args.write:
        print("No changes were made. The previous lines show paths to packages that would have been fixed.")
        print("Run this script again with the --write option to actually fix these packages.")
    else:
        print(f"{num_fixed} package(s) fixed.")

except Exception as e:
    print("Error:", e)
