# -*- coding: utf-8 -*-
"""Invalid geometry checker. Uses GEOS isValid().

Detects geometries that violate OGC Simple Feature spec:
self-intersections, unclosed rings, degenerate polygons, etc.

Fix: runs fixgeometries twice (Structure then Linework method).

Author: Loc Vu Trung tong hop vi dam me cung ban!
"""
from .base import BaseChecker


class InvalidChecker(BaseChecker):
    name = "invalid"
    display_name_en = "Invalid Geometry"
    display_name_vi = "Hinh hoc khong hop le"

    def check(self, layer, params):
        errors, details = [], []
        for feat in layer.getFeatures():
            g = feat.geometry()
            if not g or g.isNull():
                continue
            # Also check empty geometry (0 area degenerate)
            if not g.isGeosValid():
                errors.append(g)
                details.append(f"FID {feat.id()}: {g.lastError()}")
            elif g.area() == 0 and g.type() == 2:  # Polygon with 0 area
                errors.append(g)
                details.append(f"FID {feat.id()}: zero-area polygon")
        return {"error_geometries": errors, "error_features": [], "details": details}

    def fix(self, input_path, output_path, params):
        """Pass through — invalid geometry is detected but not auto-fixed.

        native:fixgeometries can silently delete features it cannot repair.
        User should review invalid geometries and fix manually in QGIS.
        """
        import shutil
        shutil.copy2(input_path, output_path)
        return output_path
