#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging

from django.conf import settings
from django.core.management.base import BaseCommand

logger = logging.getLogger(__name__)


def _app_module_name(app_label):
    """从 INSTALLED_APPS 项解析出可导入的 app 模块名（用于 fixtures.initialize）。"""
    if ".apps." in app_label:
        return app_label.split(".apps.")[0]
    return app_label


class Command(BaseCommand):
    """
    项目初始化命令: python manage.py init
    使用当前项目的 settings（django.conf.settings），确保 INSTALLED_APPS 等配置来自主工程。
    """

    def add_arguments(self, parser):
        parser.add_argument(
            "init_name",
            nargs="*",
            type=str,
        )
        parser.add_argument("-y", nargs="*")
        parser.add_argument("-Y", nargs="*")
        parser.add_argument("-n", nargs="*")
        parser.add_argument("-N", nargs="*")

    def handle(self, *args, **options):
        reset = False
        if isinstance(options.get("y"), list) or isinstance(options.get("Y"), list):
            reset = True
        if isinstance(options.get("n"), list) or isinstance(options.get("N"), list):
            reset = False
        for app in settings.INSTALLED_APPS:
            module_name = _app_module_name(app)
            try:
                exec(
                    f"""
from {module_name}.fixtures.initialize import Initialize
Initialize(reset={reset},app="{app}").run()
                """
                )
            except ModuleNotFoundError as e:
                print(f"ModuleNotFoundError,{e.args}")
        print("初始化数据完成！")
