# Drop-in installer for the YanusFACE Deploy package.
# User drags this file into the Maya viewport; Maya calls onMayaDroppedPythonFile.
#
# IMPORTANT: this file MUST keep a plugin-unique name (YanusFACE_Installer.py),
# NOT a generic "Installer.py". Maya imports a dropped file by its basename and
# caches it in sys.modules — two plugins sharing the name "Installer" would
# collide, so dropping the second one in the same session would re-run the first
# (the user would have to restart Maya). The build pipeline enforces this name
# via [project].dropin_name in tools/protect/config.toml.
import os
import sys
import traceback

import maya.cmds as cmds


def onMayaDroppedPythonFile(*args, **kwargs):
    try:
        _setup_path(args)
        _launch()
    except Exception:
        traceback.print_exc()
        cmds.confirmDialog(
            title='YanusFACE Installer Error',
            message=traceback.format_exc(),
            button=['OK'])


def _setup_path(args=()):
    # Resolve installer directory
    script_path = None
    if args and os.path.isfile(str(args[0])):
        script_path = str(args[0])
    if not script_path:
        script_path = __file__

    current_dir = os.path.dirname(os.path.abspath(script_path))
    maya_version = cmds.about(version=True)

    dev_path = os.path.join(current_dir, 'scripts', 'development')
    ver_path = os.path.join(current_dir, 'scripts', maya_version)
    script_dir = dev_path if os.path.exists(dev_path) else ver_path

    if not os.path.isdir(script_dir):
        cmds.confirmDialog(
            title='YanusFACE Installer',
            message='Scripts folder not found:\n{}'.format(script_dir),
            button=['OK'])
        return

    if script_dir not in sys.path:
        sys.path.append(script_dir)


def _launch():
    # Purge cached installer modules so a repeated drop in the SAME Maya session
    # re-imports fresh code from disk instead of reusing sys.modules entries
    # (Maya imports a dropped file by basename and caches it — see module docstring).
    for name in [k for k in list(sys.modules)
                 if k == 'YFI_Main' or k.startswith('YFI_Scripts')]:
        del sys.modules[name]

    import YFI_Main
    YFI_Main.YanusFACEInstallation()
