from collections import defaultdict

from rest_framework import serializers, status

from api.models import TtUsagePreference, TtConstraintProfile, TtSetting, TtTimeBlock, TtFreeBlock, TtResourceBreak, \
    TtMaximumWorkspan, TtMaximumHour, TtTravelTable
from api.models.audit_trail import AuditTrail
from api.models.audit_trail_details import AuditTrailDetails
from api.models.tt_location import TtLocation
from api.views.admin.base import AdminApiBase
from api.validator import BaseValidator
from api.utils import decrypt_aes_128_cbc, encrypt_aes_128_cbc, generate_kafka_data_update, log_critical_error, \
    get_exception_detail, \
    get_add_new_data, get_ip, get_old_new_data, bulk_sync_to_redis, get_multiple_old_new_data, search_old_new_data, \
    get_start_and_end_slot
from rest_framework.exceptions import ValidationError
from api.translation import __
from backend.kafka import send_request
from backend.redis_client import redis_client
from django.db.models import Prefetch

class ConstraintProfileUpdate(AdminApiBase):
    def validate_request(self,request):
        rules = {
            "id": "required|array|exists:api.TtConstraintProfile,id",
        }
        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }
        # validate id first, cause need get constraint_profile by id, if wrong id direct return error
        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()
        if error:
            raise ValidationError(error)

        edit_constraint_profile = (
            TtConstraintProfile.objects
            .select_related("department")
            .prefetch_related(
                "free_block",
                "resource_break",
                "maximum_hour",
                "maximum_workspan",
                "travel_table",
                "tag__tag" # tags means the relation add in models, __tag means the relation table tag_id get the tag object #2
            )
            .filter(id__in=request.data.get("id"))
        )
        status_code_string = ",".join(str(v) for v in TtTimeBlock.STATUS_TO_CODE.values())
        # FE will request by pattern, so can reduce the changes from FE, and BE will convert this pattern become start_slot and end_slot
        rules = {
            "name": "nullable",
            "desc": "nullable",
            "department_id": "nullable|exists:api.TtDepartment,id",
            "active_constraints": "nullable|array",
            "tag": "nullable|array|exists:api.TtTag,id",
        }

        if request.data.get("code") and edit_constraint_profile.count() == 1:
            constraint_profile = edit_constraint_profile.first()
            if request.data.get("code") != constraint_profile.code:
                rules['code'] = "nullable|not_exists:api.TtConstraintProfile,code"

        # if need rename field, can put here
        attribute = {
            # "email": __("attr.email"),
        }

        validator = BaseValidator(request.data,rules,attribute)
        error = validator.validate()

        # custom error after basic validation

        if error:
            raise ValidationError(error)

        # different from create, if FE pass in [], will skip validation but will remove all relation for this constraint_profile
        if request.data.get("active_constraints") and edit_constraint_profile.count() == 1:
            category_as_key = {}
            required_fields = {"id", "category"}
            active_constraints = request.data.get("active_constraints")
            for active_constraint in active_constraints:
                if not required_fields.issubset(active_constraint.keys()):
                    raise ValidationError({
                        "error": __('validation.invalid', field=__("attr.active_constraints")),
                        "errors": {
                            "active_constraints": __('validation.invalid', field=__("attr.active_constraints"))}
                    })
                category_as_key.setdefault(active_constraint["category"], set()).add(active_constraint["id"])
            if category_as_key:
                category_to_table = {
                    "free_block": TtFreeBlock,
                    "resource_break": TtResourceBreak,
                    "maximum_workspan": TtMaximumWorkspan,
                    "maximum_hour": TtMaximumHour,
                    "travel_table": TtTravelTable
                }
                for key, val in category_as_key.items():
                    model = category_to_table.get(key)
                    # FE passing invalid category, throw error
                    if not model:
                        raise ValidationError({
                            "error": __('validation.invalid', field=__("attr.active_constraints")),
                            "errors": {
                                "active_constraints": __('validation.invalid', field=__("attr.active_constraints"))}
                        })

                    count = model.objects.filter(id__in=val).count()

                    # if got id not found, return invalid format for active_constraints only
                    if count != len(val):
                        raise ValidationError({
                            "error": __('validation.invalid', field=__("attr.active_constraints")),
                            "errors": {
                                "active_constraints": __('validation.invalid', field=__("attr.active_constraints"))}
                        })

        return edit_constraint_profile


    def post(self, request):
        # Validate input
        try:
            edit_constraint_profile = self.validate_request(request)

            action="constraint_profile_update" # this is for audit log only

            updated = False
            update_fields = {}
            ignore_fields = ['id','active_constraints','tag','timestamp','signature']
            # if more than 1 constraint_profile edit, ignore code
            if edit_constraint_profile.count() > 1 or not request.data.get("code"):
                ignore_fields.append('code')
            valid_fields = {f.column for f in TtConstraintProfile._meta.fields}
            for key, val in request.data.items():
                if key not in ignore_fields and key in valid_fields:
                    updated = True
                    match key:
                        case _:
                            # default the key will same as db column name
                            update_fields[key] = val

            # be4 save need get the old new data already, because bulk update is no matter got change or no changes also will update
            old_new_data = get_multiple_old_new_data(edit_constraint_profile,update_fields.items(),ignore_fields,valid_fields)
            if update_fields: # 2026-04-27, ignore updated param, it is useless, this code is replace by "replace in file", so didnt remove param updated
                update_fields['updated_by'] = request.user.id
                edit_constraint_profile.update(**update_fields)

            active_constraints = {}
            if edit_constraint_profile.count() == 1 and "active_constraints" in request.data:
                # when "active_constraints" in request data, pre set all category to [] first, cause got this param means need update
                # since FE pass in is always latest active_constraints, but dunno got any things need remove or not, so default is all become empty
                active_constraints = {
                    "free_block": [],
                    "resource_break": [],
                    "maximum_workspan": [],
                    "maximum_hour": [],
                    "travel_table": [],
                }
                input_active_constraints = request.data.get("active_constraints")
                # group FE input to become needed format first, then only update the relation table
                for active_constraint in input_active_constraints:
                    active_constraints[active_constraint['category']].append(active_constraint['id'])
                for category, ids in active_constraints.items():
                    # normally category is same as the relation name inside model, if got different, can put if else to handle it
                    old_new_data = self.update_m2m_field_bulk(edit_constraint_profile,category,ids,old_new_data)

            if "tag" in request.data:
                new_ids = request.data.get("tag", [])
                old_new_data = self.update_m2m_field_bulk(edit_constraint_profile,'tag',new_ids,old_new_data,False,True)

            redis_data = {
                "update": {}
            }

            redis_constraint_profile_table = "constraint_profile"
            redis_constraint_profile_data = {}
            redis_constraint_profile_column = [
                "name", "department_id", "free_block_ids", "resource_break_ids", "maximum_workspan_ids", "maximum_hour_ids","travel_table_ids",
            ]

            # if only 1 constraint_profile, can edit code
            if edit_constraint_profile.count() == 1:
                redis_constraint_profile_column.append('code')

            constraint_profile_ids = [cp.id for cp in edit_constraint_profile]

            query_map = {
                "free_block": TtFreeBlock,
                "resource_break": TtResourceBreak,
                "maximum_workspan": TtMaximumWorkspan,
                "maximum_hour": TtMaximumHour,
                "travel_table": TtTravelTable,
            }

            relation_map = [
                "free_block",
                "resource_break",
                "maximum_workspan",
                "maximum_hour",
                "travel_table",
            ]

            prefetches = []

            for relation_name in relation_map:
                model = query_map[relation_name]

                prefetches.append(
                    Prefetch(
                        relation_name,
                        queryset=model.objects.filter(
                            status=model.STATUS_TO_CODE["active"]
                        ),
                    )
                )

            profiles = (
                TtConstraintProfile.objects
                .filter(id__in=constraint_profile_ids)
                .prefetch_related(*prefetches)
            )

            # got new data only means got update, then will for loop request.data, cause the old_new_data['new_data'] for foreign key name, like constraint_profile_id, will return in constraint_profile, so cant use it
            if old_new_data['new_data']:
                for profile in profiles:
                    # every new constraint_profile reset the redis_constraint_profile_data and append to redis_data['update']
                    redis_constraint_profile_data = {"id": profile.id}
                    for key, val in request.data.items():
                        if key == "active_constraints":
                            for relation_name in relation_map:
                                redis_constraint_profile_data[f"{relation_name}_ids"] =  sorted([
                                obj.id for obj in getattr(profile, relation_name).all()
                            ])
                        elif key in redis_constraint_profile_column:
                            redis_constraint_profile_data[key] = val

                    if len(redis_constraint_profile_data)>1:# > 1 means not only id
                        redis_data["update"].setdefault(redis_constraint_profile_table, []).append(redis_constraint_profile_data)

            bulk_sync_to_redis(redis_client,redis_data)

            if old_new_data['old_data'] or old_new_data['new_data']:
                #kafka update/ split by id
                # kafka_constraint_profile = []
                # method = "constraint_profile_update"
                # kafka_topic = self.kafka_config['MICROSERVICES_TT_TOPIC']
                # if kafka_topic:
                #     new_data = old_new_data.get("new_data")
                #     relation_fields = ["tag"]
                #     relation_data = generate_kafka_data_update(new_data, relation_fields)
                #     update_fields.pop("updated_by", None)
                #
                #     for start_pref in edit_constraint_profile:
                #         data = {"id": start_pref.id, **update_fields, **relation_data}
                #         kafka_constraint_profile.append(data)
                #     kafka_request_data = {
                #         "session_id": request.user.name,
                #         "constraint_profile": kafka_constraint_profile,
                #     }
                #     send_request(kafka_topic, kafka_request_data, None, method)

                # insert audit trail and details
                # can insert the parent first, then only insert details
                audit_trail = AuditTrail.objects.create(
                    user_id=request.user.id,
                    type=self.audit_type,
                    ip_address=get_ip(request)
                )

                name = ",".join(edit_constraint_profile.values_list("name", flat=True))
                remark_param = {
                    "name":name
                }

                # call to a function for insert details, so in future if want change to used worker, can modify in function only
                AuditTrailDetails.custom_insert(
                    audit_trail=audit_trail,
                    action=action,
                    remark_param=remark_param,
                    new_data=old_new_data['new_data'],
                    old_data=old_new_data['old_data'],
                )

            response = {

            }

            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)