"""Tests para load_geojson_polygons."""

import json
import sys
import tempfile
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from geo.load_geojson_polygons import load_geojson_polygons


def _write_geojson(data: dict) -> Path:
    f = tempfile.NamedTemporaryFile(
        mode="w", suffix=".geojson", delete=False, encoding="utf-8"
    )
    json.dump(data, f)
    f.close()
    return Path(f.name)


def test_polygon_simple_produce_1_poligono_con_1_anillo():
    geojson = {
        "type": "FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [
                        [
                            [-3.7, 40.4],
                            [-3.6, 40.4],
                            [-3.6, 40.5],
                            [-3.7, 40.5],
                            [-3.7, 40.4],
                        ]
                    ],
                },
                "properties": {},
            }
        ],
    }
    path = _write_geojson(geojson)
    try:
        result = load_geojson_polygons(path)
        assert len(result) == 1, f"expected 1 polygon, got {len(result)}"
        assert len(result[0]) == 1, "expected 1 ring"
        assert len(result[0][0]) >= 4, "ring should have >= 4 points"
        assert isinstance(result[0][0][0], tuple), "points should be tuples"
    finally:
        path.unlink(missing_ok=True)


def test_archivo_inexistente_lanza_FileNotFoundError():
    import pytest

    with pytest.raises(FileNotFoundError):
        load_geojson_polygons("/tmp/this_file_does_not_exist_xyz.geojson")
