"""Tests para load_boundary_gdf."""

import json
import sys
import tempfile
from pathlib import Path

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

from geo.load_boundary_gdf import load_boundary_gdf


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_retorna_GeoDataFrame_con_CRS_EPSG4326():
    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": {"name": "test"},
            }
        ],
    }
    path = _write_geojson(geojson)
    try:
        gdf = load_boundary_gdf(path, crs="EPSG:4326")
        import geopandas as gpd  # type: ignore

        assert isinstance(gdf, gpd.GeoDataFrame), "result should be a GeoDataFrame"
        assert gdf.crs is not None, "CRS should be set"
        assert gdf.crs.to_epsg() == 4326, f"expected EPSG:4326, got {gdf.crs}"
        assert len(gdf) == 1, f"expected 1 feature, got {len(gdf)}"
    finally:
        path.unlink(missing_ok=True)


def test_archivo_inexistente_lanza_FileNotFoundError():
    import pytest

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