import ctypes
import os
import math
import glob

class C:
    def __init__(self):
        # Look for the compiled .so or .pyd file inside the package folder
        pkg_dir = os.path.dirname(__file__)
        lib_pattern = os.path.join(pkg_dir, "libcalc*")
        found_libs = glob.glob(lib_pattern)

        if not found_libs:
            raise FileNotFoundError("The C engine was not compiled correctly during installation.")
            
        self.lib = ctypes.CDLL(found_libs[0])
        self.lib.solve.argtypes = [ctypes.c_char_p]
        self.lib.solve.restype = ctypes.c_double

    def evaluate(self, equation: str):
        if not equation or not isinstance(equation, str):
            return 0.0
        clean_eq = equation.strip().encode('utf-8')
    
        result = self.lib.solve(clean_eq)
        if math.isnan(result):
            return "Error: No solution or invalid math"
        if math.isinf(result):
            return "Error: Division by zero"
    
        return int(result) if result.is_integer() else result

# Singleton instance
c = C()