from django.core.management import BaseCommand
import re

from django.db.models import Q

from assignments.models import Assignment
from surveys.models import Survey


class Command(BaseCommand):
    """
    usage: `python manage.py migrate_surveys_assignments_titles
    """

    def handle(self, *args, **options):
        self.stdout.write("this")
        assignments = Assignment.objects.filter(
            Q(owner__isnull=True) | Q(owner__username="guru")
        )
        count = 0
        matched = 0
        pattern = re.compile(
            r"^(\w)\s(?:\dLJ\s)?(LF\d{1,2})\s(?:[MT]\d{1,2}\s)?(A\d{1,2}\w?)"
        )
        module_pattern = re.compile(r"^\w+\s(\d{1,2})")  # Modul 1 --> M1
        level_pattern = re.compile(r"^(\d)\.\s\w+")  # 1. Lehrjahr --> LJ1
        # pattern1 = re.compile(r"^\w\sLF\d{1,2}\sA\d{1,2}\w?:")  # D LF1 A12: Bla
        assert module_pattern.match("Modul 1")
        assert module_pattern.match("Modul 24")
        assert level_pattern.match("1. Lehrjahr")
        assert pattern.match("D LF1 A12: Bla")
        assert pattern.match("D LF1 A12g: Bla")
        # pattern2 = re.compile(
        #     r"^\w\sLF\d{1,2}\sT\d{1,2}\sA\d{1,2}\w?:"
        # )  # D LF1 T9 A12: Bla
        assert pattern.match("D LF1 T9 A2a: Bla")
        assert pattern.match("D LF12 T9 A12: Bla")
        # pattern3 = re.compile(
        #     r"^\w\s\dLJ\sLF\d{1,2}\sM\d{1,2}\sA\d{1,2}\w?:"
        # )  # D 1LJ LF1 M2 A12: Bla
        assert pattern.match("D 1LJ LF1 M2 A12: Bla")
        assert pattern.match("D 1LJ LF1 M2 A12s: Bla")
        for assignment in assignments:
            count += 1
            match = pattern.match(assignment.title)
            if (
                match
                is not None
                # pattern1.match(assignment.title) is not None
                # or pattern2.match(assignment.title) is not None
                # or pattern3.match(assignment.title) is not None
            ):
                # print(match.groups())
                try:
                    module = assignment.module
                    module_match = module_pattern.match(module.meta_title)
                    level = module.level
                    level_match = level_pattern.match(level.name)
                    new_title = f"{match.group(1)} LJ{level_match.group(1)} {match.group(2)} M{module_match.group(1)} {match.group(3)}"
                    self.stdout.write(new_title)
                    assignment.title = new_title
                    matched += 1
                except AttributeError:
                    self.stderr.write(f"assignment {assignment.id} failed")
            # else:
            # self.stdout.write(assignment.title)

        Assignment.objects.bulk_update(assignments, ["title"])

        self.stdout.write(f"assignments: {matched}/{count}")
        count = 0
        matched = 0
        surveys = Survey.objects.all()
        for survey in surveys:
            count += 1
            match = pattern.match(survey.title)
            if (
                match
                is not None
                # pattern1.match(survey.title) is not None
                # or pattern2.match(survey.title) is not None
                # or pattern3.match(survey.title) is not None
            ):
                try:
                    module = survey.module
                    module_match = module_pattern.match(module.meta_title)
                    level = module.level
                    level_match = level_pattern.match(level.name)
                    new_title = f"{match.group(1)} LJ{level_match.group(1)} {match.group(2)} M{module_match.group(1)} {match.group(3)}"
                    self.stdout.write(new_title)
                    survey.title = new_title
                    matched += 1
                except AttributeError:
                    self.stderr.write(f"survey {survey.id} failed")

            # else:
            # self.stdout.write(survey.title)
        Survey.objects.bulk_update(surveys, ["title"])
        self.stdout.write(f"surveys: {matched}/{count}")
