import antimeridian
from shapely.geometry import shape, mapping
from shapely.geometry.polygon import orient

def process_polygons(feature_type, polygon_patch, feature_id, upper_fl=None, lower_fl=None):
    exterior = polygon_patch.find(".//exterior//posList").text.strip().split()
    interiors = [int.text.strip().split() for int in polygon_patch.findall(".//interior//posList")]
    exterior = [[float(y), float(x)] for x, y in zip(exterior[::2], exterior[1::2])]
    interiors = [[[float(y), float(x)] for x, y in zip(int[::2], int[1::2])] for int in interiors]

    feature = {
        "type": "Feature",
        "geometry": {
            "type": "Polygon",
            "coordinates": [exterior, *interiors],
        },
        "properties": {
            "feature_id": feature_id,
            "phenomenon": feature_type,
            "upper_fl": upper_fl,
            "lower_fl": lower_fl,
        }
    }
    raw_shape = shape(feature["geometry"])
    properly_wound_shape = orient(raw_shape, sign=1.0)
    feature["geometry"] = mapping(properly_wound_shape)

    fixed_feature = antimeridian.fix_geojson(feature)
    return fixed_feature

def process_points(feature_type, point, feature_id, upper_fl=None, lower_fl=None):
    coords = point.find(".//pos").text.strip().split()
    coords[1], coords[0] = float(coords[0]), float(coords[1])  # Swap to [lat, lon]
    feature = {
        "type": "Feature",
        "geometry": {
            "type": "Point",
            "coordinates": coords,
        },
        "properties": {
            "feature_id": feature_id,
            "phenomenon": feature_type,
            "upper_fl": upper_fl,
            "lower_fl": lower_fl,
        }
    }
    return feature

def process_lines(feature_type, line, feature_id, upper_fl=None, lower_fl=None):
    coords = line.find(".//posList").text.strip().split()
    coords = [[float(y), float(x)] for x, y in zip(coords[::2], coords[1::2])]
    feature = {
        "type": "Feature",
        "geometry": {
            "type": "LineString",
            "coordinates": coords,
        },
        "properties": {
            "feature_id": feature_id,
            "phenomenon": feature_type,
            "upper_fl": upper_fl,
            "lower_fl": lower_fl,
        }
    }
    fixed_feature = antimeridian.fix_geojson(feature)
    return fixed_feature

