import datetime
from collections import defaultdict

from rest_framework import serializers, status

from api.models import TtDepartment, TtZone, TtAvailability, TtStartPreference, TtUsagePreference, TtTag, TtSetting, \
    TtModule, TtAcademicTerm, TtActivityType, TtStaff, TtLocation, TtSuitability, TtActivityTemplate, TtWeekPattern, \
    TtWeek, TtPosModuleGroupModule
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import decrypt_aes_128_cbc, encrypt_aes_128_cbc, log_critical_error, get_exception_detail, \
    calculate_preset_pattern_time
from rest_framework.exceptions import ValidationError
from api.translation import __


class ActivityTemplateRules(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "module_id": "nullable|exists:api.TtModule,id",
            "academic_term_id": "required|exists:api.TtAcademicTerm,id",
            "activity_template_id": "nullable|exists:api.TtActivityTemplate,id",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get activity_template by id, if wrong id direct return error
        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)
        # custom error after basic validation

        if error:
            raise ValidationError(error)

    def post(self, request):
        # Validate input
        try:
            self.api_log_skip_outgoing_data=True
            self.validate_request(request)
            academic_term_id = request.data.get("academic_term_id")
            academic_term = TtAcademicTerm.objects.filter(id=academic_term_id).prefetch_related("week").first()
            activity_template_id = request.data.get("activity_template_id")
            module_id = request.data.get("module_id")

            activity_templates = (
                TtActivityTemplate.objects
                .select_related("department","academic_term", "week_pattern","module","activity_type","zone", "availability", "start_preference", "usage_preference")
                .prefetch_related(
                    "staff",
                    "staff_suitability",
                    "location",
                    "location_suitability",
                    "week",
                    "week_pattern__week",
                    "tag__tag"
                    # tags means the relation add in models, __tag means the relation table tag_id get the tag object #2
                )
                .filter(module_id=module_id,academic_term_id=academic_term_id)
            )

            info = []
            if activity_templates:
                for activity_template in activity_templates:
                    info_data = {
                        "id": activity_template.id,
                        "code": activity_template.code,
                        "name": activity_template.name,
                        "desc": activity_template.desc,
                        "duration": activity_template.duration,
                        "activity_type_id": activity_template.activity_type_id,
                        "department_id": activity_template.department_id,
                        "sequence_number": activity_template.sequence_number,
                        "zone_id": activity_template.zone_id,
                        "academic_term_id": activity_template.academic_term_id,
                        "planned_size": activity_template.planned_size,
                        "module_id": activity_template.module_id,
                        "module_code": activity_template.module.code if activity_template.module else None,
                        "module_name": activity_template.module.name if activity_template.module else None,
                        "module_size": activity_template.module.planned_size if activity_template.module else None,
                        "staff_requirement": activity_template.staff_requirement,
                        "staff": [
                            {"id": staff.id, "name": staff.name}
                            for staff in activity_template.staff.all()
                        ],
                        "staff_suitability": [
                            {"id": staff.id, "name": staff.name}
                            for staff in activity_template.staff_suitability.all()
                        ],
                        "location_requirement": activity_template.location_requirement,
                        "location": [
                            {"id": location.id, "name": location.name}
                            for location in activity_template.location.all()
                        ],
                        "location_suitability": [
                            {"id": location.id, "name": location.name}
                            for location in activity_template.location_suitability.all()
                        ],
                        "week_pattern_id": activity_template.week_pattern_id,
                        "week_pattern_name": activity_template.week_pattern.name if activity_template.week_pattern else "-",
                        "week_pattern": [week.id for week in activity_template.week.all()],
                        "availability_id": activity_template.availability_id,
                        "availability_name": activity_template.availability.name if activity_template.availability else "-",
                        "availability_pattern": activity_template.availability_pattern,
                        "usage_preference_id": activity_template.usage_preference_id,
                        "usage_preference_name": activity_template.usage_preference.name if activity_template.usage_preference else "-",
                        "usage_preference_pattern": activity_template.usage_preference_pattern,
                        "start_preference_id": activity_template.start_preference_id,
                        "start_preference_name": activity_template.start_preference.name if activity_template.start_preference else "-",
                        "start_preference_pattern": activity_template.start_preference_pattern,
                        "tag": [t.tag_id for t in activity_template.tag.all()],
                    }

                    for i in range(1, 11):
                        extra_data_field = f"extra_data_{i}"
                        info_data[extra_data_field] = getattr(activity_template, extra_data_field, None)

                    if info_data['staff_requirement'] == 0:
                        info_data['staff_requirement'] = activity_template.staff.count()

                    if info_data['location_requirement'] == 0:
                        info_data['location_requirement'] = activity_template.location.count()
                    info.append(info_data)

            data = {}
            data['delete_confirmation_api'] = True
            data["allow_remove"] = [
                "desc",
                "department_id",
                "sequence_number",
                "zone_id",
                "staff",
                "staff_suitability",
                "location",
                "location_suitability",
                "week_pattern",
                "week_pattern_id",
                "availability_id",
                "availability_pattern",
                "start_preference_id",
                "start_preference_pattern",
                "usage_preference_id",
                "usage_preference_pattern",
                "tag",
                *[f"extra_data_{i}" for i in range(1, 11)]
            ]
            setting_params = {
                "minute_per_slot",
                "slot_per_day",
                "slot_per_week",
            }
            data['based_setting'] = TtSetting.get_multiple_setting(setting_params)

            models = {

                "academic_term": (TtAcademicTerm,["id", "code", "name", "start_time", "end_time", "default_availability","default_usage", "default_start"]),
                "department": (TtDepartment, ["id", "code", "name"]),
                "zone": (TtZone, ["id", "code", "name"]),
                "staff": (TtStaff, ["id", "code", "name"]),
                "location": (TtLocation, ["id", "code", "name"]),
                "activity_type": (TtActivityType, ["id", "code", "name","color"]),
                "availability": (TtAvailability, ["id", "code", "name", "pattern"]),
                "start_preference": (TtStartPreference, ["id","code", "name", "pattern"]),
                "usage_preference": (TtUsagePreference, ["id", "code", "name", "pattern"]),
                "tag": (TtTag, ["id", "code", "name"]),
            }

            for key, (model, fields) in models.items():
                if key == "academic_term":
                    data[key] = list(
                        model.objects.filter(id=academic_term_id,status=model.STATUS_TO_CODE['active']).values(*fields)
                    )
                else:
                    data[key] = list(
                        model.objects.filter(status=model.STATUS_TO_CODE['active']).values(*fields)
                    )

            data['staff_suitability'] = []
            data['location_suitability'] = []

            staff_suitability_ids = []
            location_suitability_ids = []
            # after selected suitability in template, if remove staff/location in suitability, when update again will cant show in the list to choose, so having this handle

            if activity_template_id:
                activity_template = TtActivityTemplate.objects.filter(id=activity_template_id).prefetch_related("staff_suitability","location_suitability").first()
                staff_suitability_ids = [s.id for s in activity_template.staff_suitability.all()]
                location_suitability_ids = [l.id for l in activity_template.location_suitability.all()]
            suitabilities = TtSuitability.objects.filter(status=TtSuitability.STATUS_TO_CODE['active']).prefetch_related("staff","location").order_by(self.list_default_order_column).all()

            for suitability in suitabilities:
                if suitability.staff.exists() or suitability.id in staff_suitability_ids:
                    data['staff_suitability'].append({
                        "id": suitability.id,
                        "code": suitability.code,
                        "name": suitability.name,
                        "items": [s.name for s in suitability.staff.all()],
                    })

                if suitability.location.exists() or suitability.id in location_suitability_ids:
                    data['location_suitability'].append({
                        "id": suitability.id,
                        "code": suitability.code,
                        "name": suitability.name,
                        "items": [l.name for l in suitability.location.all()],
                    })

            # for type in ["availability", "usage_preference", "start_preference"]:
            #     for val in data[type]:
            #         start_end_time = calculate_preset_pattern_time(type, val.get('pattern'), data['based_setting'].get("minute_per_slot"),data['based_setting'].get("slot_per_day"))
            #         val['start_time'] = start_end_time.get("start_time")
            #         val['end_time'] = start_end_time.get("end_time")

            # duration based on academic term and based setting

            minute_per_slot = int(data["based_setting"]["minute_per_slot"])
            start = datetime.datetime.strptime("00:00", "%H:%M")
            data["duration"] = []
            current = start
            current_minute = 0

            total_slot = 48

            for slot in range(0, total_slot + 1):
                # dun show slot 0
                if slot != 0:
                    data["duration"].append({
                        "minute": current_minute,
                        "slot": slot,
                        "name": f"{current.strftime('%H:%M')} {__("attr.hours")} ({slot} {__('attr.period')})"
                    })
                current += datetime.timedelta(minutes=minute_per_slot)
                current_minute += minute_per_slot

            week_patterns = TtWeekPattern.objects.prefetch_related("week").filter(academic_term_id=academic_term_id,status=TtWeekPattern.STATUS_TO_CODE['active'])
            data["week_pattern"] = []
            for week_pattern in week_patterns:
                data['week_pattern'].append({
                    "id": week_pattern.id,
                    "code": week_pattern.code,
                    "name": week_pattern.name,
                    "academic_term_id": week_pattern.academic_term_id,
                    "pattern": week_pattern.week.all().values("week","start_date"),
                })
            data['week'] = list(academic_term.week.all().values("id","week","start_date").order_by("week"))
            # data['week'] = list(TtWeek.objects.filter(id__in=week_ids).values("id","week").order_by("week"))

            # 2026-02-03 NOT SURE WHAT IS THE PURPOSE TO GET POS MODULE GROUP MODULE FOR SELECTION IN FE, SO CHANGE TO DIRECT GET FROM MODULE
            # FOR DISPLAY MODULE NAME ONLY
            # pos_module_group_modules = (
            #     TtPosModuleGroupModule.objects
            #     .filter(pos_module_group__pos__academic_term_id=academic_term_id)
            #     .select_related("pos_module_group", "pos_module_group__module_group", "module")
            # )
            #
            # # make the pos_module_group_modules data key by pos_id, so it can filter inside pos rules
            # modules_by_pos = defaultdict(list)
            # pos_used_module = defaultdict(set)
            # used_module = set()
            #
            # data['module'] = []
            # for val in pos_module_group_modules:
            #     pos_id = val.pos_module_group.pos_id
            #
            #     # Skip duplicate module_code for same POS
            #     if val.module.id in pos_used_module[pos_id]:
            #         continue
            #
            #     pos_used_module[pos_id].add(val.module.id)
            #     modules_by_pos[pos_id].append({
            #         # "pos_module_group_module_id": val.id,
            #         "module_id": val.module.id,
            #         "module_name": val.module.name,
            #         "module_code": val.module.code,
            #         # "module_group_name": val.pos_module_group.module_group.name,
            #     })
            #
            #     if val.module.id not in used_module:
            #         used_module.add(val.module.id)
            #         data['module'].append({
            #             "id": val.module.id,
            #             "name": val.module.name,
            #             "code": val.module.code,
            #         })

            data['module'] = []
            modules = TtModule.objects.filter(academic_term_id=academic_term_id)
            for val in modules:
                data['module'].append({
                    "id": val.id,
                    "name": val.name,
                    "code": val.code,
                })

            response = {
                "info": info,
                "rules": data,
            }

            return self.api_response(data=response)
        except ValidationError as e:
            first_message = e.detail['error']
            errors = e.detail['errors']
            return self.api_response(error=first_message,errors=errors,code=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            e_details = get_exception_detail(e)
            log_critical_error(user_id=None,descr=e_details['descr'],url=e_details['url'],trace=e_details['trace'])
            return self.api_response(error=__("message.internal_server_error"),code=status.HTTP_500_INTERNAL_SERVER_ERROR)