import os
import random
from datetime import datetime, timedelta

import djclick as click
from dateutil.relativedelta import MO, relativedelta, TH, TU
from django.utils import timezone

from vbv_lernwelt.assignment.creators.create_assignments import (
    create_uk_basis_prep_assignment,
    create_uk_condition_acceptance,
    create_uk_fahrzeug_casework,
    create_uk_fahrzeug_prep_assignment,
    create_uk_fr_basis_prep_assignment,
    create_uk_fr_fahrzeug_casework,
    create_uk_fr_fahrzeug_prep_assignment,
    create_uk_fr_kickoff_prep_assignment,
    create_uk_fr_reflection,
    create_uk_it_basis_prep_assignment,
    create_uk_it_fahrzeug_casework,
    create_uk_it_fahrzeug_prep_assignment,
    create_uk_it_kickoff_prep_assignment,
    create_uk_it_reflection,
    create_uk_kickoff_prep_assignment,
    create_uk_reflection,
    create_vv_einkommenssicherung_casework,
    create_vv_gesundheit_casework,
    create_vv_gewinnen_casework,
    create_vv_reflection,
)
from vbv_lernwelt.assignment.models import Assignment, AssignmentCompletionStatus
from vbv_lernwelt.assignment.services import update_assignment_completion
from vbv_lernwelt.assignment.tests.assignment_factories import AssignmentListPageFactory
from vbv_lernwelt.competence.create_uk_competence_profile import (
    create_uk_competence_profile,
    create_uk_fr_competence_profile,
    create_uk_it_competence_profile,
)
from vbv_lernwelt.competence.create_uk_training_competence_profile import (
    create_uk_fr_training_competence_profile,
    create_uk_it_training_competence_profile,
    create_uk_training_competence_profile,
)
from vbv_lernwelt.competence.create_vv_new_competence_profile import (
    create_vv_new_competence_profile,
)
from vbv_lernwelt.competence.models import PerformanceCriteria
from vbv_lernwelt.core.constants import TEST_MENTOR1_USER_ID
from vbv_lernwelt.core.create_default_users import default_users
from vbv_lernwelt.core.models import User
from vbv_lernwelt.course.consts import (
    COURSE_MOTORFAHRZEUG_PRUEFUNG_ID,
    COURSE_TEST_ID,
    COURSE_UK,
    COURSE_UK_FR,
    COURSE_UK_IT,
    COURSE_UK_TRAINING,
    COURSE_UK_TRAINING_FR,
    COURSE_UK_TRAINING_IT,
    COURSE_VERSICHERUNGSVERMITTLERIN_FR_ID,
    COURSE_VERSICHERUNGSVERMITTLERIN_ID,
    COURSE_VERSICHERUNGSVERMITTLERIN_IT_ID,
    COURSE_VERSICHERUNGSVERMITTLERIN_PRUEFUNG_ID,
)
from vbv_lernwelt.course.creators.test_course import (
    create_edoniq_test_assignment,
    create_test_course,
)
from vbv_lernwelt.course.creators.uk_course import (
    create_competence_navi,
    create_uk_fr_learning_path,
    create_uk_it_learning_path,
    create_uk_learning_path,
)
from vbv_lernwelt.course.creators.uk_training_course import (
    create_uk_training_learning_path,
)
from vbv_lernwelt.course.creators.versicherungsvermittlerin import (
    create_versicherungsvermittlerin_with_categories,
)
from vbv_lernwelt.course.models import (
    Course,
    CoursePage,
    CourseSession,
    CourseSessionUser,
)
from vbv_lernwelt.course.services import mark_course_completion
from vbv_lernwelt.course_session.models import (
    CourseSessionAssignment,
    CourseSessionAttendanceCourse,
)
from vbv_lernwelt.importer.services import (
    import_course_sessions_from_excel,
    import_students_from_excel,
    import_trainers_from_excel_for_training,
)
from vbv_lernwelt.learning_mentor.models import LearningMentor
from vbv_lernwelt.learnpath.create_vv_new_learning_path import (
    create_vv_motorfahrzeug_pruefung_learning_path,
    create_vv_new_learning_path,
    create_vv_pruefung_learning_path,
)
from vbv_lernwelt.learnpath.models import (
    Circle,
    LearningContent,
    LearningContentAssignment,
    LearningContentAttendanceCourse,
)
from vbv_lernwelt.media_files.create_default_documents import (
    create_default_collections,
    create_default_content_documents,
    create_default_user_documents,
)
from vbv_lernwelt.media_files.create_default_images import create_default_images
from vbv_lernwelt.media_library.create_default_media_library import (
    create_default_media_library,
)

ADMIN_EMAILS = ["info@iterativ.ch", "admin"]


@click.command()
@click.option(
    "--course",
    "-c",
    multiple=True,
    default=[
        COURSE_TEST_ID,
        COURSE_UK,
        COURSE_VERSICHERUNGSVERMITTLERIN_ID,
        # COURSE_VERSICHERUNGSVERMITTLERIN_FR_ID,
        # COURSE_VERSICHERUNGSVERMITTLERIN_IT_ID,
        # COURSE_UK_FR,
        # COURSE_UK_IT,
        # COURSE_UK_TRAINING,
        # COURSE_UK_TRAINING_FR,
        # COURSE_UK_TRAINING_IT,
    ],
)
def command(course):
    print("Creating default courses", course)

    create_default_collections()
    create_default_content_documents()
    create_default_user_documents()
    create_default_images()

    if COURSE_VERSICHERUNGSVERMITTLERIN_ID in course:
        create_versicherungsvermittlerin_course()

    if COURSE_VERSICHERUNGSVERMITTLERIN_FR_ID in course:
        create_versicherungsvermittlerin_course(
            course_id=COURSE_VERSICHERUNGSVERMITTLERIN_FR_ID, language="fr"
        )
    if COURSE_VERSICHERUNGSVERMITTLERIN_IT_ID in course:
        create_versicherungsvermittlerin_course(
            course_id=COURSE_VERSICHERUNGSVERMITTLERIN_IT_ID, language="it"
        )

    if COURSE_VERSICHERUNGSVERMITTLERIN_PRUEFUNG_ID in course:
        create_versicherungsvermittlerin_pruefung_course()

    if COURSE_UK in course:
        create_course_uk_de()
        create_course_uk_de_course_sessions()
        create_course_uk_de_completion_data(
            CourseSession.objects.get(title="Demo üK 2023 DE")
        )
        create_course_uk_de_assignment_completion_data(
            assignment=Assignment.objects.get(
                slug="überbetriebliche-kurse-assignment-überprüfen-einer-motorfahrzeugs-versicherungspolice"
            ),
            course_session=CourseSession.objects.get(title="Demo üK 2023 DE"),
            user=User.objects.get(email="lina.egger@example.com"),
        )

    if COURSE_UK_FR in course:
        create_course_uk_fr()

    if COURSE_UK_IT in course:
        create_course_uk_it()

    if COURSE_TEST_ID in course:
        create_test_course(with_sessions=True)

    if COURSE_UK_TRAINING in course:
        create_course_training_de()

    if COURSE_UK_TRAINING_FR in course:
        create_course_training_fr()

    if COURSE_UK_TRAINING_IT in course:
        create_course_training_it()


def create_versicherungsvermittlerin_course(
    course_id=COURSE_VERSICHERUNGSVERMITTLERIN_ID, language="de"
):
    names = {
        "de": "Versicherungsvermittler/-in",
        "fr": "Intermédiaire d’assurance",
        "it": "Intermediario/a assicurativo/a",
    }
    # Versicherungsvermittler/in mit neuen Circles
    course = create_versicherungsvermittlerin_with_categories(
        course_id=course_id,
        title=names[language],
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )

    create_vv_new_competence_profile(course_id=course_id)
    create_default_media_library(course_id=course_id)
    create_vv_einkommenssicherung_casework(course_id=course_id)
    create_vv_gesundheit_casework(course_id=course_id)
    create_vv_gewinnen_casework(course_id=course_id)
    create_vv_reflection(course_id=course_id)
    create_vv_new_learning_path(course_id=course_id)

    cs = CourseSession.objects.create(course_id=course_id, title=names[language])

    for assignment in Assignment.objects.all():
        if assignment.get_course().id == course_id:
            CourseSessionAssignment.objects.get_or_create(
                course_session=cs,
                learning_content=assignment.find_attached_learning_content(),
            )

    if language == "de":
        for user_data in default_users:
            CourseSessionUser.objects.create(
                course_session=cs,
                user=User.objects.get(username=user_data["email"]),
            )

        csu = CourseSessionUser.objects.create(
            course_session=cs,
            user=User.objects.get(username="student-vv@eiger-versicherungen.ch"),
        )
        expert1 = CourseSessionUser.objects.create(
            course_session=cs,
            user=User.objects.get(username="expert-vv.expert1@eiger-versicherungen.ch"),
            role=CourseSessionUser.Role.EXPERT,
        )

        expert2 = CourseSessionUser.objects.create(
            course_session=cs,
            user=User.objects.get(username="expert-vv.expert2@eiger-versicherungen.ch"),
            role=CourseSessionUser.Role.EXPERT,
        )

        expert3 = CourseSessionUser.objects.create(
            course_session=cs,
            user=User.objects.get(username="expert-vv.expert3@eiger-versicherungen.ch"),
            role=CourseSessionUser.Role.EXPERT,
        )

        lemme = LearningMentor.objects.create(
            mentor=User.objects.get(id=TEST_MENTOR1_USER_ID),
            course=cs.course,
        )

        lemme.participants.add(csu)

        experts = [expert1, expert2, expert3]

        circles = Circle.objects.filter(
            slug__startswith="versicherungsvermittler-in-lp"
        )

        # for i, circle in enumerate(circles):
        #     expert = experts[i % len(experts)]
        #     expert.expert.add(circle)
        #     create_feedback(circle, cs, 3)

        for admin_email in ADMIN_EMAILS:
            CourseSessionUser.objects.create(
                course_session=cs,
                user=User.objects.get(email=admin_email),
            )


def create_versicherungsvermittlerin_pruefung_course(
    course_id=COURSE_VERSICHERUNGSVERMITTLERIN_PRUEFUNG_ID, language="de"
):
    names = {
        "de": "Versicherungsvermittler/-in VBV Prüfung",
        "fr": "Intermédiaire d’assurance AFA Examen",
        "it": "Intermediario/a assicurativo/a AFA Esame",
    }
    # Versicherungsvermittler/in mit neuen Circles
    course = create_versicherungsvermittlerin_with_categories(
        course_id=course_id,
        title=names[language],
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )

    create_vv_new_competence_profile(course_id=course_id)
    create_default_media_library(course_id=course_id)
    create_vv_reflection(course_id=course_id)

    CourseSession.objects.create(course_id=course_id, title=names[language])

    create_vv_pruefung_learning_path(course_id=course_id)


def create_motorfahrzeug_pruefung_course(
    course_id=COURSE_MOTORFAHRZEUG_PRUEFUNG_ID, language="de"
):
    names = {
        "de": "Motorfahrzeug Versicherungsvermittler/-in VBV Prüfung",
        "fr": "Véhicules à moteur Intermédiaire d’assurance AFA Examen",
        "it": "Veicolo a motore Intermediario/a assicurativo/a AFA Esame",
    }
    # Versicherungsvermittler/in mit neuen Circles
    course = create_versicherungsvermittlerin_with_categories(
        course_id=course_id,
        title=names[language],
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )

    create_vv_new_competence_profile(course_id=course_id)
    create_default_media_library(course_id=course_id)
    create_vv_reflection(course_id=course_id)

    CourseSession.objects.create(course_id=course_id, title=names[language])

    create_vv_motorfahrzeug_pruefung_learning_path(course_id=course_id)


def create_course_uk_de(course_id=COURSE_UK, lang="de"):
    names = {
        "de": "Überbetriebliche Kurse",
        "fr": "Cours interentreprises",
        "it": "Corsi interaziendali",
    }
    course = create_versicherungsvermittlerin_with_categories(
        course_id=course_id, title=names[lang]
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )

    competence_certificate = create_competence_navi(course_id=COURSE_UK)

    create_uk_kickoff_prep_assignment(course_id=course_id)
    create_uk_condition_acceptance(course_id=course_id)
    create_uk_basis_prep_assignment(course_id=course_id)
    create_uk_fahrzeug_casework(
        course_id=course_id, competence_certificate=competence_certificate
    )
    create_uk_fahrzeug_prep_assignment(course_id=course_id)
    create_uk_reflection(course_id=course_id)
    create_edoniq_test_assignment(
        course_id=course_id,
        title="Edoniq Wissens- und Verständisfragen - Circle Basis",
        competence_certificate=competence_certificate,
    )

    # learning path
    create_uk_learning_path(course_id=course_id)
    create_uk_competence_profile(course_id=course_id)
    create_default_media_library(course_id=course_id)

    create_default_collections()
    create_default_content_documents()


def create_course_uk_de_course_sessions():
    course = Course.objects.get(id=COURSE_UK)

    cs = CourseSession.objects.create(
        course_id=COURSE_UK,
        title="Demo üK 2023 DE",
    )

    csac = CourseSessionAttendanceCourse.objects.create(
        course_session=cs,
        learning_content=LearningContentAttendanceCourse.objects.get(
            slug="überbetriebliche-kurse-lp-circle-fahrzeug-lc-präsenzkurs-fahrzeug"
        ),
        location="Handelsschule KV Bern, Zimmer 123, Eigerstrasse 16, 3012 Bern",
        trainer="Roland Grossenbacher, roland.grossenbacher@helvetia.ch",
    )
    tuesday_in_two_weeks = (
        datetime.now() + relativedelta(weekday=TU(2)) + relativedelta(weeks=2)
    )
    csac.due_date.start = timezone.make_aware(
        tuesday_in_two_weeks.replace(hour=8, minute=30, second=0, microsecond=0)
    )
    csac.due_date.end = timezone.make_aware(
        tuesday_in_two_weeks.replace(hour=17, minute=0, second=0, microsecond=0)
    )
    csac.due_date.save()

    csa = CourseSessionAssignment.objects.create(
        course_session=cs,
        learning_content=LearningContentAssignment.objects.get(
            slug=f"{course.slug}-lp-circle-fahrzeug-lc-überprüfen-einer-motorfahrzeug-versicherungspolice"
        ),
    )
    next_thursday = datetime.now() + relativedelta(weekday=TH(2))
    csa.submission_deadline.start = timezone.make_aware(
        (next_thursday + relativedelta(weeks=3)).replace(
            hour=23, minute=59, second=59, microsecond=0
        )
    )
    csa.submission_deadline.save()
    csa.evaluation_deadline.start = timezone.make_aware(
        (next_thursday + relativedelta(weeks=5)).replace(
            hour=23, minute=59, second=59, microsecond=0
        )
    )
    csa.evaluation_deadline.save()

    csa = CourseSessionAssignment.objects.create(
        course_session=cs,
        learning_content=LearningContentAssignment.objects.get(
            slug=f"{course.slug}-lp-circle-fahrzeug-lc-fahrzeug-mein-erstes-auto"
        ),
    )
    next_monday = datetime.now() + relativedelta(weekday=MO(2))
    csa.submission_deadline.start = timezone.make_aware(
        (next_monday + relativedelta(weeks=1)).replace(
            hour=23, minute=59, second=59, microsecond=0
        )
    )
    csa.submission_deadline.save()

    # figma demo users and data
    csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="patrizia.huggel@eiger-versicherungen.ch"),
        role=CourseSessionUser.Role.EXPERT,
    )
    csu.expert.add(Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-kickoff"))
    csu.expert.add(
        Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-haushalt-teil-1")
    )
    csu.expert.add(Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-fahrzeug"))
    csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="andreas.feuz@eiger-versicherungen.ch"),
        role=CourseSessionUser.Role.EXPERT,
    )
    csu.expert.add(
        Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-haushalt-teil-2")
    )
    csu.expert.add(Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-basis"))
    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="michael.meier@example.com"),
    )
    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="lina.egger@example.com"),
    )
    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="evelyn.schmid@example.com"),
    )

    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="christoph.bosshard@vbv-afa.ch"),
    )

    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="axel.manderbach@lernetz.ch"),
    )

    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="patrick.muster@eiger-versicherungen.ch"),
    )

    # TODO: feedback must now contain a `feedback_user`
    # create_feedback(
    #     Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-kickoff"),
    #     cs,
    #     3,
    # )
    # create_feedback(
    #     Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-haushalt-teil-2"),
    #     cs,
    #     14,
    # )
    # create_feedback(
    #     Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-basis"), cs, 4
    # )


def create_course_uk_fr():
    # Überbetriebliche Kurse FR
    course = create_versicherungsvermittlerin_with_categories(
        course_id=COURSE_UK_FR, title="Cours interentreprises"
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )

    create_uk_condition_acceptance(course_id=COURSE_UK_FR)
    create_uk_fr_kickoff_prep_assignment(course_id=COURSE_UK_FR)
    create_uk_fr_basis_prep_assignment(course_id=COURSE_UK_FR)
    create_uk_fr_fahrzeug_casework(course_id=COURSE_UK_FR)
    create_uk_fr_fahrzeug_prep_assignment(course_id=COURSE_UK_FR)
    create_uk_fr_reflection(course_id=COURSE_UK_FR)
    create_uk_fr_learning_path(course_id=COURSE_UK_FR)
    create_uk_fr_competence_profile(course_id=COURSE_UK_FR)
    create_default_media_library(course_id=COURSE_UK_FR)

    cs = CourseSession.objects.create(
        course_id=COURSE_UK_FR,
        title="Demo ci 2023 FR",
    )

    csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="geraldine.kolly@assurance.ch"),
        role=CourseSessionUser.Role.EXPERT,
    )
    csu.expert.add(
        Circle.objects.get(slug="cours-interentreprises-lp-circle-lancement")
    )
    _csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="luca.dupont@assurance.ch"),
    )
    csu = CourseSessionUser.objects.create(
        course_session=cs,
        user=User.objects.get(username="andreas.feuz@eiger-versicherungen.ch"),
        role=CourseSessionUser.Role.EXPERT,
    )

    for fr_circle in Circle.objects.filter(
        slug__startswith="cours-interentreprises-lp"
    ):
        csu.expert.add(fr_circle)


def create_course_uk_it():
    # Überbetriebliche Kurse FR
    course = create_versicherungsvermittlerin_with_categories(
        course_id=COURSE_UK_IT, title="Corso interaziendale"
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )
    create_uk_condition_acceptance(course_id=COURSE_UK_IT)
    create_uk_it_kickoff_prep_assignment(course_id=COURSE_UK_IT)
    create_uk_it_basis_prep_assignment(course_id=COURSE_UK_IT)
    create_uk_it_fahrzeug_casework(course_id=COURSE_UK_IT)
    create_uk_it_fahrzeug_prep_assignment(course_id=COURSE_UK_IT)
    create_uk_it_reflection(course_id=COURSE_UK_IT)
    create_uk_it_learning_path(course_id=COURSE_UK_IT)
    create_uk_it_competence_profile(course_id=COURSE_UK_IT)
    create_default_media_library(course_id=COURSE_UK_IT)

    _cs = CourseSession.objects.create(
        course_id=COURSE_UK_IT,
        title="Demo ci 2023 IT",
    )


def create_course_uk_de_assignment_completion_data(assignment, course_session, user):
    subtasks = assignment.filter_user_subtasks(subtask_types=["user_text_input"])
    for index, subtask in enumerate(subtasks):
        user_text = f"Lorem ipsum dolor sit amet... {index}"

        update_assignment_completion(
            assignment_user=user,
            assignment=assignment,
            learning_content_page=assignment.learningcontentassignment_set.first(),
            course_session=course_session,
            completion_data={
                subtask["id"]: {
                    "user_data": {"text": user_text},
                }
            },
        )
    update_assignment_completion(
        assignment_user=user,
        assignment=assignment,
        learning_content_page=assignment.learningcontentassignment_set.first(),
        course_session=course_session,
        completion_status=AssignmentCompletionStatus.SUBMITTED,
    )


def create_course_uk_de_completion_data(course_session):
    circles = Circle.objects.filter(slug__startswith="überbetriebliche-kurse-lp-circle")
    for circle in circles:
        for index, lc in enumerate(circle.get_descendants().type(LearningContent)):
            mark_course_completion(
                page=lc,
                user=User.objects.get(email="lina.egger@example.com"),
                course_session=course_session,
                completion_status="SUCCESS",
            )

            random_number = random.randint(1, 3)
            if index % random_number == 0:
                mark_course_completion(
                    page=lc,
                    user=User.objects.get(email="michael.meier@example.com"),
                    course_session=course_session,
                    completion_status="SUCCESS",
                )

    performance_criteria = (
        CoursePage.objects.get(course_id=COURSE_UK)
        .get_descendants()
        .type(PerformanceCriteria)
    )
    for index, pc in enumerate(performance_criteria):
        mark_course_completion(
            page=pc,
            user=User.objects.get(email="lina.egger@example.com"),
            course_session=course_session,
            completion_status="SUCCESS",
        )

        random_number = random.randint(1, 4)
        if index % random_number == 0:
            mark_course_completion(
                page=pc,
                user=User.objects.get(email="michael.meier@example.com"),
                course_session=course_session,
                completion_status="SUCCESS",
            )
        if index % random_number == 1:
            mark_course_completion(
                page=pc,
                user=User.objects.get(email="michael.meier@example.com"),
                course_session=course_session,
                completion_status="FAIL",
            )


def create_course_training_de():
    # Test Lehrgang für üK Trainer
    course = create_versicherungsvermittlerin_with_categories(
        course_id=COURSE_UK_TRAINING, title="myVBV Training"
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )
    create_uk_fahrzeug_casework(course_id=COURSE_UK_TRAINING)
    create_uk_fahrzeug_prep_assignment(course_id=COURSE_UK_TRAINING)
    create_uk_reflection(course_id=COURSE_UK_TRAINING)

    create_uk_training_learning_path(course_id=COURSE_UK_TRAINING)
    create_uk_training_competence_profile(course_id=COURSE_UK_TRAINING)
    create_default_media_library(course_id=COURSE_UK_TRAINING)

    current_dir = os.path.dirname(os.path.realpath(__file__))
    print(current_dir)
    course = Course.objects.get(id=COURSE_UK_TRAINING)
    import_course_sessions_from_excel(
        f"{current_dir}/../../../importer/tests/Schulungen_Durchfuehrung_Trainer.xlsx",
        course=course,
        restrict_language="de",
    )
    import_trainers_from_excel_for_training(
        f"{current_dir}/../../../importer/tests/Schulungen_Durchfuehrung_Trainer.xlsx",
        course=course,
    )
    import_students_from_excel(
        f"{current_dir}/../../../importer/tests/Schulungen_Teilnehmende.xlsx",
    )

    for i, cs in enumerate(CourseSession.objects.filter(course_id=COURSE_UK_TRAINING)):
        create_course_session_assignments(
            cs,
            f"{course.slug}-lp-circle-fahrzeug-lc-überprüfen-einer-motorfahrzeug-versicherungspolice",
            i=i,
        )

    # attach users as trainers to ÜK course
    course_uk = Course.objects.filter(id=COURSE_UK).first()
    if course_uk:
        users = [
            csu.user
            for csu in CourseSessionUser.objects.filter(
                course_session__course_id=COURSE_UK_TRAINING
            )
        ]

        cs = CourseSession.objects.get(course_id=COURSE_UK, title="Demo üK 2023 DE")

        for user in users:
            csu, _created = CourseSessionUser.objects.get_or_create(
                course_session_id=cs.id, user_id=user.id
            )
            csu.role = CourseSessionUser.Role.EXPERT
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-kickoff")
            )
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-basis")
            )
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-fahrzeug")
            )

            csu.save()


def create_course_session_assignments(course_session, assignment_slug, i=1):
    csa = CourseSessionAssignment.objects.create(
        course_session=course_session,
        learning_content=LearningContentAssignment.objects.get(slug=assignment_slug),
    )
    if course_session.start_date is None:
        course_session.start_date = datetime.now() + timedelta(days=i * 12)
        course_session.save()

    submission_deadline = csa.submission_deadline
    if submission_deadline:
        submission_deadline.start = course_session.start_date + timedelta(days=14)
        submission_deadline.save()
    evaluation_deadline = csa.evaluation_deadline
    if evaluation_deadline:
        evaluation_deadline.start = course_session.start_date + timedelta(days=28)
        evaluation_deadline.save()


def create_course_training_fr():
    # Test Lehrgang für üK Trainer FR
    course = create_versicherungsvermittlerin_with_categories(
        course_id=COURSE_UK_TRAINING_FR, title="myVBV Training (FR)"
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )
    create_uk_fr_fahrzeug_casework(course_id=COURSE_UK_TRAINING_FR)
    create_uk_fr_fahrzeug_prep_assignment(course_id=COURSE_UK_TRAINING_FR)
    create_uk_fr_reflection(course_id=COURSE_UK_TRAINING_FR)

    create_uk_training_learning_path(course_id=COURSE_UK_TRAINING_FR)
    create_uk_fr_training_competence_profile(course_id=COURSE_UK_TRAINING_FR)
    create_default_media_library(course_id=COURSE_UK_TRAINING_FR)

    current_dir = os.path.dirname(os.path.realpath(__file__))
    print(current_dir)
    course = Course.objects.get(id=COURSE_UK_TRAINING_FR)
    import_course_sessions_from_excel(
        f"{current_dir}/../../../importer/tests/Schulungen_Durchfuehrung_Trainer.xlsx",
        restrict_language="fr",
        course=course,
    )
    import_trainers_from_excel_for_training(
        f"{current_dir}/../../../importer/tests/Schulungen_Durchfuehrung_Trainer.xlsx",
        course=course,
        language="fr",
    )
    import_students_from_excel(
        f"{current_dir}/../../../importer/tests/Schulungen_Teilnehmende.xlsx",
    )

    for cs in CourseSession.objects.filter(course_id=COURSE_UK_TRAINING_FR):
        # cs.assignment_details_list = [
        #     {
        #         "learningContentId": LearningContentAssignment.objects.get(
        #             slug=f"{course.slug}-lp-circle-véhicule-lc-vérification-dune-police-dassurance-de-véhicule-à-moteur"
        #         ).id,
        #         "submissionDeadlineDateTimeUtc": "2023-06-13T19:00:00Z",
        #         "evaluationDeadlineDateTimeUtc": "2023-06-27T19:00:00Z",
        #     },
        #     {
        #         "learningContentId": LearningContentAssignment.objects.get(
        #             slug=f"{course.slug}-lp-circle-véhicule-lc-véhicule-à-moteur-ma-première-voiture"
        #         ).id,
        #         "submissionDeadlineDateTimeUtc": "2023-06-13T19:00:00Z",
        #         "evaluationDeadlineDateTimeUtc": "2023-06-27T19:00:00Z",
        #     },
        # ]
        cs.save()

    # attach users as trainers to ÜK course
    course_uk = Course.objects.filter(id=COURSE_UK_FR).first()
    if course_uk:
        users = [
            csu.user
            for csu in CourseSessionUser.objects.filter(
                course_session__course_id=COURSE_UK_TRAINING_FR
            )
        ]

        cs = CourseSession.objects.get(
            course_id=COURSE_UK_FR,
            title="Demo ci 2023 FR",
        )

        for user in users:
            csu, _created = CourseSessionUser.objects.get_or_create(
                course_session_id=cs.id, user_id=user.id
            )
            csu.role = CourseSessionUser.Role.EXPERT
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-kickoff")
            )
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-basis")
            )
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-fahrzeug")
            )

            csu.save()


def create_course_training_it():
    # Test Lehrgang für üK Trainer FR
    course = create_versicherungsvermittlerin_with_categories(
        course_id=COURSE_UK_TRAINING_IT, title="myVBV Training (IT)"
    )

    # assignments create assignments parent page
    _assignment_list_page = AssignmentListPageFactory(
        parent=course.coursepage,
    )
    create_uk_it_fahrzeug_casework(course_id=COURSE_UK_TRAINING_IT)
    create_uk_it_fahrzeug_prep_assignment(course_id=COURSE_UK_TRAINING_IT)
    create_uk_it_reflection(course_id=COURSE_UK_TRAINING_IT)

    create_uk_training_learning_path(course_id=COURSE_UK_TRAINING_IT)
    create_uk_it_training_competence_profile(course_id=COURSE_UK_TRAINING_IT)
    create_default_media_library(course_id=COURSE_UK_TRAINING_IT)

    current_dir = os.path.dirname(os.path.realpath(__file__))
    print(current_dir)
    course = Course.objects.get(id=COURSE_UK_TRAINING_IT)
    import_course_sessions_from_excel(
        f"{current_dir}/../../../importer/tests/Schulungen_Durchfuehrung_Trainer.xlsx",
        restrict_language="it",
        course=course,
    )
    import_trainers_from_excel_for_training(
        f"{current_dir}/../../../importer/tests/Schulungen_Durchfuehrung_Trainer.xlsx",
        course=course,
        language="it",
    )
    import_students_from_excel(
        f"{current_dir}/../../../importer/tests/Schulungen_Teilnehmende.xlsx",
    )

    for cs in CourseSession.objects.filter(course_id=COURSE_UK_TRAINING_IT):
        # cs.assignment_details_list = [
        #     {
        #         "learningContentId": LearningContentAssignment.objects.get(
        #             slug=f"{course.slug}-lp-circle-veicolo-lc-verifica-di-una-polizza-di-assicurazione-veicoli-a-motore"
        #         ).id,
        #         "submissionDeadlineDateTimeUtc": "2023-06-20T19:00:00Z",
        #         "evaluationDeadlineDateTimeUtc": "2023-06-27T19:00:00Z",
        #     },
        #     {
        #         "learningContentId": LearningContentAssignment.objects.get(
        #             slug=f"{course.slug}-lp-circle-veicolo-lc-veicolo-la-mia-prima-auto"
        #         ).id,
        #         "submissionDeadlineDateTimeUtc": "2023-06-20T19:00:00Z",
        #         "evaluationDeadlineDateTimeUtc": "2023-06-27T19:00:00Z",
        #     },
        # ]
        cs.save()

    # attach users as trainers to ÜK course
    course_uk = Course.objects.filter(id=COURSE_UK_IT).first()
    if course_uk:
        users = [
            csu.user
            for csu in CourseSessionUser.objects.filter(
                course_session__course_id=COURSE_UK_TRAINING_IT
            )
        ]

        cs = CourseSession.objects.get(
            course_id=COURSE_UK_IT,
            title="Demo ci 2023 IT",
        )

        for user in users:
            csu, _created = CourseSessionUser.objects.get_or_create(
                course_session_id=cs.id, user_id=user.id
            )
            csu.role = CourseSessionUser.Role.EXPERT
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-kickoff")
            )
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-basis")
            )
            csu.expert.add(
                Circle.objects.get(slug="überbetriebliche-kurse-lp-circle-fahrzeug")
            )

            csu.save()
