import ctypes
import os
import glob

class Math:
    def __init__(self):
        # Find where the package is installed
        base_path = os.path.dirname(os.path.abspath(__file__))
        
        # Search for the compiled binary (e.g., libcalc.cpython-313-x86_64.so)
        lib_pattern = os.path.join(base_path, "libcalc*.so")
        lib_files = glob.glob(lib_pattern)

        if lib_files:
            self.lib = ctypes.CDLL(lib_files[0])
        else:
            raise ImportError(f"acentic: Binary not found in {base_path}")

        # --- THE HANDSHAKE ---
        self.lib.compile.restype = ctypes.c_void_p
        self.lib.compile.argtypes = [ctypes.c_char_p]
        self.lib.execute_bytecode.restype = ctypes.c_double
        self.lib.execute_bytecode.argtypes = [ctypes.c_void_p, ctypes.c_double]
        self.lib.execute_bulk.restype = ctypes.c_double
        self.lib.execute_bulk.argtypes = [ctypes.c_void_p, ctypes.c_int]

    def compile(self, equation: str):
        return self.lib.compile(equation.encode('utf-8'))

    def evaluate(self, target, x=0.0, iterations=1):
        if isinstance(target, str):
            target = self.compile(target)
        if iterations > 1:
            return self.lib.execute_bulk(target, int(iterations))
        return self.lib.execute_bytecode(target, float(x))

# Create the instance for the user
math = Math()