# -*- coding: utf-8 -*-
"""Tiny polygon checker — iterative merge to neighbor.

Merges polygons smaller than threshold into adjacent polygon
with longest shared boundary. Max 20 iterations.

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


class TinyPolygonChecker(BaseChecker):
    name = "tiny_polygon"
    display_name_en = "Tiny Polygons"
    display_name_vi = "Polygon nho (Tiny)"

    def check(self, layer, params):
        min_area = params.get("tiny_min_area", 0.0) * 10000  # ha → m²
        if min_area <= 0:
            return {"error_geometries": [], "error_features": [], "details": []}
        errors = []
        for feat in layer.getFeatures():
            g = feat.geometry()
            if g and not g.isNull() and g.area() > 0 and g.area() < min_area:
                errors.append(g)
        return {"error_geometries": errors, "error_features": [],
                "details": [f"Area: {g.area():.4f} m2" for g in errors]}

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

        Rationale: deleting or merging features reduces feature count,
        which is destructive. User should review 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
