# QGIS
from qgis.core import Qgis, QgsGeometry

# Project
from qsfcgal.toolbelt.log_handler import PlgLogger

# Third-part
try:
    import pysfcgal.sfcgal as sfcgal

    PlgLogger.log(message="Dependencies loaded from Python installation.")
except Exception:
    PlgLogger.log(
        message="Import from Python installation failed. Trying to load from "
        "embedded external libs.",
        log_level=Qgis.MessageLevel.Info,
        push=False,
    )
    import site

    from qsfcgal.__about__ import DIR_PLUGIN_ROOT

    site.addsitedir(DIR_PLUGIN_ROOT / "embedded_external_libs")
    import pysfcgal.sfcgal as sfcgal


def QgsGeometry_to_SFCGAL(geom: QgsGeometry) -> sfcgal.Geometry:
    """Convert QgsGeometry object to SFCGAL geometry

    :param geom: Input geometry (@geometry)
    :type geom: QgsGeometry
    :return: Output geometry
    :rtype: pysfcgal.sfcgal.Geometry
    """
    try:
        geom_sfcgal = sfcgal.Geometry.from_wkb(geom.asWkb().data())
    except Exception as e:
        PlgLogger.log(
            message=f"Error : {e}", push=False, log_level=Qgis.MessageLevel.Info
        )
        raise TypeError(e)
    return geom_sfcgal


def SFCGAL_to_QgsGeometry(geom: sfcgal.Geometry) -> QgsGeometry:
    """Convert SFCGAL geometry object to QgsGeometry

    :param geom: _description_
    :type geom: sfcgal.Geometry
    """
    try:
        qgs_geometry = QgsGeometry()
        qgs_geometry.fromWkb(geom.to_wkb())
    except Exception as e:
        PlgLogger.log(
            message=f"Erreur : {e}", push=False, log_level=Qgis.MessageLevel.Info
        )
        raise TypeError(e)

    return qgs_geometry


def multipolygon_to_polygons(multipolygon_geom: QgsGeometry) -> list[QgsGeometry]:
    """
    Converts a multipolygon geometry to a list of polygon geometries.
    This does not support 3D multi polygons.

    This function checks if the provided geometry is of type multipolygon
    and returns a list of individual polygon geometries.

    :param multipolygon_geom: QgsGeometry of type multipolygon.
    :return: A list of QgsGeometry objects of type polygon.
    :raises ValueError: If the input geometry is not a multipolygon.
    """
    # Check if the geometry is a multipolygon
    if multipolygon_geom.isMultipart():
        polygons = multipolygon_geom.asMultiPolygon()
        polygon_geometries = [
            QgsGeometry.fromPolygonXY(polygon) for polygon in polygons
        ]
        return polygon_geometries
    else:
        raise ValueError("Input must be a geometry of type multipolygon.")
