#!/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


def _has_fixtures_initialize(module_name):
    """仅当存在 {module_name}.fixtures.initialize 时才返回 True，避免对无该结构的 app 报错。"""
    try:
        from importlib.util import find_spec

        return find_spec(f"{module_name}.fixtures.initialize") is not None
    except (ModuleNotFoundError, ValueError):
        return False


class Command(BaseCommand):
    """
    项目初始化命令: python manage.py init
    使用当前项目的 settings（django.conf.settings），确保 INSTALLED_APPS 等配置来自主工程。
    仅对提供 fixtures.initialize 的 app 执行初始化，其余 app 静默跳过。
    """

    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)
            if not _has_fixtures_initialize(module_name):
                continue
            try:
                exec(
                    f"""
from {module_name}.fixtures.initialize import Initialize
Initialize(reset={reset},app="{app}").run()
                """
                )
            except Exception as e:
                logger.exception("初始化 %s 失败: %s", app, e)
                self.stderr.write(self.style.ERROR(f"初始化 {app} 失败: {e}"))
        self.stdout.write(self.style.SUCCESS("初始化数据完成！"))
