import os
import sys

import clr  # type: ignore

# Path to the compiled AdvChkSys .NET DLL (adjust as needed)
DLL_PATH = os.path.abspath(
    os.path.join(
        os.path.dirname(__file__),
        "..",
        "..",
        "AdvChkSys",
        "bin",
        "Debug",
        "netstandard2.1",
        "AdvChkSys.dll",
    )
)

if not os.path.exists(DLL_PATH):
    raise FileNotFoundError(f"Could not find AdvChkSys.dll at {DLL_PATH}")

sys.path.append(os.path.dirname(DLL_PATH))
clr.AddReference("AdvChkSys")

# Import .NET types

from System import Byte  # type: ignore  # noqa: E402

import AdvChkSys  # type: ignore  # noqa: E402
import AdvChkSys.Manager  # type: ignore  # noqa: E402
import AdvChkSys.Constraints  # type: ignore  # noqa: E402


def get_version():
    """Return the AdvChkSys library version."""
    return AdvChkSys.AdvChkSys.Version  # type: ignore


def create_2d_manager(constraints=None):
    """Create a 2D chunk manager (byte type)."""
    if constraints is None:
        constraints = AdvChkSys.Constraints.WorldConstraints()  # type: ignore
    # Use generic type with System.Byte
    return AdvChkSys.Manager.ChunkManager2D[Byte](constraints)  # type: ignore


def create_3d_manager(constraints=None):
    """Create a 3D chunk manager (byte type)."""
    if constraints is None:
        constraints = AdvChkSys.Constraints.WorldConstraints()  # type: ignore
    # Use generic type with System.Byte
    return AdvChkSys.Manager.ChunkManager3D[Byte](constraints)  # type: ignore


def create_constraints(
    min_x=None, max_x=None, min_y=None, max_y=None, max_loaded=None
):
    """Create a WorldConstraints object."""
    wc = AdvChkSys.Constraints.WorldConstraints()  # type: ignore
    if min_x is not None:
        wc.MinChunkX = min_x
    if max_x is not None:
        wc.MaxChunkX = max_x
    if min_y is not None:
        wc.MinChunkY = min_y
    if max_y is not None:
        wc.MaxChunkY = max_y
    if max_loaded is not None:
        wc.MaxLoadedChunks = max_loaded
    return wc
