#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 初始化

import json
import logging
import os

from django.apps import apps

from django_base_ai.system.models import Users

logger = logging.getLogger(__name__)
from django_base_ai.system.views.api_white_list import ApiWhiteListInitSerializer
from django_base_ai.system.views.dept import DeptInitSerializer
from django_base_ai.system.views.dictionary import DictionaryInitSerializer
from django_base_ai.system.views.menu import MenuInitSerializer
from django_base_ai.system.views.role import RoleInitSerializer
from django_base_ai.system.views.system_config import SystemConfigInitSerializer
from django_base_ai.system.views.tags import TagsInitSerializer
from django_base_ai.system.views.user import UsersInitSerializer
from django_base_ai.utils.core_initialize import CoreInitialize


class Initialize(CoreInitialize):
    def init_dept(self):
        """
        初始化部门信息
        """
        self.init_base(DeptInitSerializer, unique_fields=["name", "parent", "key"])

    def init_role(self):
        """
        初始化角色信息
        """
        self.init_base(RoleInitSerializer, unique_fields=["key"])

    def _ensure_bootstrap_user(self):
        """
        在任意 init 前执行：若 init_users.json 存在且非空，则创建/更新其第一个用户并设为 request.user，
        避免整段 init 期间 request.user 为 AnonymousUser 导致误写入 AnonymousUser 记录。
        """
        path_file = os.path.join(
            apps.get_app_config(self.app.split(".")[-1]).path,
            "fixtures",
            "init_users.json",
        )
        if not os.path.isfile(path_file):
            return
        with open(path_file, encoding="utf-8") as f:
            user_list = json.load(f)
        if not user_list:
            return
        first = user_list[0]
        filter_data = {"username": first["username"]} if "username" in first else {}
        instance = Users.objects.filter(**filter_data).first()
        first["reset"] = self.reset
        serializer = UsersInitSerializer(instance, data=first, request=self.request)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        bootstrap_user = Users.objects.filter(username=first["username"]).first()
        if bootstrap_user:
            self.request.user = bootstrap_user

    def init_users(self):
        """
        初始化用户信息（run 开始时已通过 _ensure_bootstrap_user 将 request.user 设为真实用户）
        """
        self.init_base(UsersInitSerializer, unique_fields=["username"])

    def init_tags(self):
        """
        初始化标签
        """
        self.init_base(TagsInitSerializer, unique_fields=["name"])

    def init_menu(self):
        """
        初始化菜单信息
        """
        self.init_base(MenuInitSerializer, unique_fields=["name", "component"])

    def init_api_white_list(self):
        """
        初始API白名单
        """
        self.init_base(
            ApiWhiteListInitSerializer,
            unique_fields=[
                "url",
                "method",
            ],
        )

    def init_dictionary(self):
        """
        初始化字典表
        """
        self.init_base(
            DictionaryInitSerializer,
            unique_fields=[
                "value",
                "parent",
            ],
        )

    def init_system_config(self):
        """
        初始化系统配置表
        """
        self.init_base(
            SystemConfigInitSerializer,
            unique_fields=[
                "key",
                "parent",
            ],
        )

    def run(self):
        logger.info("系统初始化开始 app=%s", self.app)
        # 在任意 init 前先确保有一个真实用户并设为 request.user，避免整段 init 期间 request.user 为 AnonymousUser 导致误写库
        self._ensure_bootstrap_user()
        self.init_dept()
        self.init_role()
        self.init_users()
        self.init_tags()
        self.init_menu()
        self.init_api_white_list()
        self.init_dictionary()
        self.init_system_config()
        logger.info("系统初始化完成 app=%s", self.app)


if __name__ == "__main__":
    Initialize(app="admin.system").run()
