# -*- coding: utf-8 -*-
"""Unclosed ring checker — first vertex must equal last vertex.

Handles both simple Polygon and MultiPolygon geometries.

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


class UnclosedChecker(BaseChecker):
    name = "unclosed"
    display_name_en = "Unclosed Rings"
    display_name_vi = "Vong khong khep kin"

    def check(self, layer, params):
        errors = []
        for feat in layer.getFeatures():
            g = feat.geometry()
            if not g or g.isNull():
                continue
            # Collect all rings from polygon or multipolygon
            all_rings = []
            if g.isMultipart():
                mp = g.asMultiPolygon()
                if mp:
                    for polygon in mp:
                        all_rings.extend(polygon)
            else:
                poly = g.asPolygon()
                if poly:
                    all_rings = poly

            for ring in all_rings:
                if len(ring) >= 2:
                    first, last = ring[0], ring[-1]
                    if abs(first.x() - last.x()) > 1e-10 or \
                       abs(first.y() - last.y()) > 1e-10:
                        errors.append(g)
                        break
        return {"error_geometries": errors, "error_features": [], "details": []}

    def fix(self, input_path, output_path, params):
        """Pass through — unclosed rings are detected but not auto-fixed.

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