# -*- coding: utf-8 -*-
import os
import sys

import nuke

def _get_nuke_major_version():
    try:
        if hasattr(nuke, "NUKE_VERSION_MAJOR"):
            return int(nuke.NUKE_VERSION_MAJOR)
        env = getattr(nuke, "env", {})
        if type(env) is dict and "NukeVersionMajor" in env:
            return int(env["NukeVersionMajor"])
    except Exception:
        pass
    return 0

_NUKE_MAJOR = _get_nuke_major_version()

if _NUKE_MAJOR < 13:
    def show_dialog():
        pass

else:
    import importlib

    _SUPPORTED_PYTHON_SUBDIRS = {
        (3, 7): "py37",
        (3, 9): "py39",
        (3, 10): "py310",
        (3, 11): "py311",
    }

    _package_dir = os.path.dirname(__file__)
    _py_version = (sys.version_info[0], sys.version_info[1])
    _sub_dir_name = _SUPPORTED_PYTHON_SUBDIRS.get(_py_version)
    _lib_path = None

    def _notify(message):
        try:
            nuke.message(message)
        except Exception:
            print(message)

    if _sub_dir_name:
        _lib_path = os.path.join(_package_dir, _sub_dir_name)
        if os.path.isdir(_lib_path):
            if _lib_path not in sys.path:
                sys.path.insert(0, _lib_path)
        else:
            _notify("MissingRelinker 错误: 找不到适用于 Python {}.{} 的核心库目录: {}".format(_py_version[0], _py_version[1], _sub_dir_name))
    else:
        print("MissingRelinker 警告: 当前 Python 版本 {}.{} 不受支持。".format(_py_version[0], _py_version[1]))

    def _import_core_module(module_name):
        errors = []
        for candidate in (module_name, __name__ + "." + module_name):
            try:
                return importlib.import_module(candidate)
            except ImportError as exc:
                errors.append(str(exc))
        raise ImportError("; ".join(errors))

    get_error_nodes = None
    collect_error_node_file_infos = None
    find_replacement_for_path = None
    find_replacement_and_bounds = None

    try:
        scanner = _import_core_module("scanner")
        searcher = _import_core_module("searcher")

        get_error_nodes = scanner.get_error_nodes
        collect_error_node_file_infos = getattr(scanner, "collect_error_node_file_infos", None)
        find_replacement_for_path = searcher.find_replacement_for_path
        find_replacement_and_bounds = searcher.find_replacement_and_bounds

    except ImportError as exc:
        print("MissingRelinker 加载核心模块失败: {}".format(exc))
        if _lib_path and _lib_path in sys.path:
            sys.path.remove(_lib_path)

    __all__ = [
        "show_dialog",
        "get_error_nodes",
        "collect_error_node_file_infos",
        "find_replacement_for_path",
        "find_replacement_and_bounds",
    ]

    def _resolve_qtwidgets():
        try:
            from PySide2 import QtWidgets
            return QtWidgets
        except Exception:
            pass
        try:
            from PySide6 import QtWidgets
            return QtWidgets
        except Exception:
            pass
        from PyQt5 import QtWidgets
        return QtWidgets

    def _dialog_exec(dialog):
        runner = getattr(dialog, "exec_", None)
        if callable(runner):
            return int(runner())
        runner = getattr(dialog, "exec", None)
        if callable(runner):
            return int(runner())
        raise RuntimeError("当前 Qt 对话框对象不支持 exec/exec_")

    def _close_existing_dialogs(QtWidgets):
        try:
            app = QtWidgets.QApplication.instance()
            if app is None:
                return
            for widget in app.topLevelWidgets():
                try:
                    if widget.objectName() in ("MissingRelinkerDialog", "ActivationDialog"):
                        widget.close()
                except Exception:
                    continue
        except Exception:
            pass

    def show_dialog():
        try:
            relinker_ui = _import_core_module("relinker_ui")
            cloud_license = _import_core_module("cloud_license")
        except Exception as exc:
            _notify("无法加载核心模块，请确认插件完整性：{}".format(exc))
            return

        try:
            is_activated, machine_code = cloud_license.check_license()
        except Exception as exc:
            _notify("验证许可时发生错误: {}".format(exc))
            return

        try:
            QtWidgets = _resolve_qtwidgets()
            _close_existing_dialogs(QtWidgets)
        except Exception as exc:
            _notify("Qt 加载失败：{}".format(exc))
            return

        try:
            if is_activated:
                dialog = relinker_ui.MissingRelinkerDialog()
                _dialog_exec(dialog)
                return

            auth_dialog = cloud_license.ActivationDialog(machine_code)
            result = _dialog_exec(auth_dialog)
            
            if result == 1:
                dialog = relinker_ui.MissingRelinkerDialog()
                _dialog_exec(dialog)
                
        except Exception as exc:
            _notify("界面显示失败：{}".format(exc))
