# -*- coding: utf-8 -*-
"""Sliver polygon detector — P/sqrt(A) compactness ratio.

A sliver is a long, narrow polygon with high perimeter-to-area ratio.
Compactness = P / sqrt(A) — higher = more elongated.
Threshold default: 20.0 (a 1×100 rectangle gives ~20.2).

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


class SliverChecker(BaseChecker):
    name = "sliver"
    display_name_en = "Sliver Polygons"
    display_name_vi = "Vung hinh kim (Sliver)"

    def _compactness(self, geometry):
        area = geometry.area()
        if area <= 0:
            return float('inf')
        return geometry.length() / math.sqrt(area)

    def check(self, layer, params):
        max_area = params.get("sliver_max_area", 1.0) * 10000  # ha → m²
        ratio_thr = params.get("sliver_ratio", 20.0)
        slivers = []
        for feat in layer.getFeatures():
            g = feat.geometry()
            if not g or g.isNull():
                continue
            if g.area() <= 0:
                continue
            if g.area() < max_area and self._compactness(g) > ratio_thr:
                slivers.append(g)
        return {"error_geometries": slivers, "error_features": [],
                "details": [f"Ratio: {self._compactness(g):.1f}" for g in slivers]}

    def fix(self, input_path, output_path, params):
        """Pass through — slivers are detected but never auto-deleted.

        Rationale: deleting features is destructive and irreversible.
        User should review sliver locations and fix manually.
        """
        from qgis.core import (
            QgsVectorLayer, QgsVectorFileWriter,
            QgsCoordinateTransformContext)
        layer = QgsVectorLayer(input_path, "in", "ogr")
        opts = QgsVectorFileWriter.SaveVectorOptions()
        opts.driverName = "GPKG"
        opts.forceMulti = True
        opts.includeZ = True
        QgsVectorFileWriter.writeAsVectorFormatV3(
            layer, output_path, QgsCoordinateTransformContext(), opts)
        return output_path
