"""Register the Kindred solver with the KCSolve solver registry."""

import logging

import FreeCAD


class _FreeCADLogHandler(logging.Handler):
    """Route Python logging to FreeCAD's Console."""

    def emit(self, record):
        msg = self.format(record) + "\n"
        if record.levelno >= logging.ERROR:
            FreeCAD.Console.PrintError(msg)
        elif record.levelno >= logging.WARNING:
            FreeCAD.Console.PrintWarning(msg)
        elif record.levelno >= logging.INFO:
            FreeCAD.Console.PrintLog(msg)
        else:
            FreeCAD.Console.PrintLog(msg)


def _setup_logging():
    """Attach FreeCAD log handler to the kindred_solver logger."""
    logger = logging.getLogger("kindred_solver")
    if not logger.handlers:
        handler = _FreeCADLogHandler()
        handler.setFormatter(logging.Formatter("%(name)s: %(message)s"))
        logger.addHandler(handler)
        logger.setLevel(logging.DEBUG)


try:
    import kcsolve
    from kindred_solver import KindredSolver

    _setup_logging()
    kcsolve.register_solver("kindred", KindredSolver)
    FreeCAD.Console.PrintLog("kindred-solver registered\n")
except Exception as exc:
    FreeCAD.Console.PrintWarning(f"kindred-solver: registration failed: {exc}\n")
