import os
from aacommpy.category import categories
from aacommpy.settings import AACOMM_DLL_PATH, NET48, get_configured_framework

def _configure_runtime():
    """Configure pythonnet runtime based on the selected .NET framework.

    Must be called before 'import clr'. On pythonnet 3.x this selects
    coreclr (for net6.0/net8.0) or netfx (for net48). On pythonnet 2.x
    this is a no-op since set_runtime does not exist.
    """
    fw = get_configured_framework()
    try:
        from pythonnet import set_runtime
        if fw != NET48:
            from clr_loader import get_coreclr
            set_runtime(get_coreclr())
        else:
            from clr_loader import get_netfx
            set_runtime(get_netfx())
    except ImportError:
        pass  # pythonnet 2.x — no runtime config needed
    except RuntimeError:
        pass  # Runtime already set (e.g. user configured it before importing aacommpy)

_configure_runtime()

import clr

def _auto_install_aacomm():
    """Automatically install AAComm NuGet package if not found."""
    print("AAComm not found. Installing AAComm NuGet package...")
    from aacommpy.nugetmanagement import download_nuget_exe, download_aacomm_nuget
    download_nuget_exe()
    download_aacomm_nuget()
    print("AAComm installation complete.")

if not os.path.isfile(AACOMM_DLL_PATH):
    _auto_install_aacomm()

if os.path.isfile(AACOMM_DLL_PATH):
    clr.AddReference(AACOMM_DLL_PATH)
    for category in categories:
        if category["enable"]:
            exec(f"from {category['from']} import {category['name']}")
    __all__ = [category["name"] for category in categories if category["enable"]]
else:
    raise RuntimeError("AAComm installation failed. Please run 'aacommpy install' manually.")
