from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from numbas_lti.models import Exam
from pathlib import Path

def find_xslt_js(root):
    for d, ds, fs in root.walk():
        for f in fs:
            p = d / f
            if p.suffix == '.js':
                with open(p) as f:
                    for line in f:
                        if 'XSLT' in line:
                            return True
                    

class Command(BaseCommand):
    help = 'Add the XSLT polyfill to old exam packages.'

    def handle(self, *args, **options):
        for exam in Exam.objects.all():
            root = Path(exam.extracted_path)

            index_path = root / 'index.html'

            try:
                with open(index_path) as f:
                    index_html = f.read()
            except FileNotFoundError:
                continue

            if 'xslt-polyfill' in index_html:
                continue

            if not find_xslt_js(root):
                continue

            index_html = index_html.replace('</head>', f'    <script src="{settings.STATIC_URL}xslt-polyfill.min.js"></script>\n</head>')
            with open(index_path, 'w') as f:
                f.write(index_html)

        print(f"All exam packages have been updated to load the XSLT polyfill.")
