import os
import json

# Root directory where the folders are located
ROOT_DIR = "./"
OUTPUT_FILES = {}

def get_insert_query(entity_id, entity_type, geometry):
    """Generate SQL insert query for bounds."""
    # If it's a GeometryCollection, extract and convert to MultiPolygon
    if geometry.get('type') == 'GeometryCollection':
        geometry = {
            "type": "MultiPolygon",
            "coordinates": [
                geom["coordinates"] for geom in geometry["geometries"] if geom["type"] == "Polygon"
            ]
        }

    geojson_str = json.dumps(geometry).replace("'", "''")  # Escape single quotes for SQL

    query = f"""
INSERT INTO bounds (entity_id, entity_type, geometry)
VALUES ({entity_id}, '{entity_type}', 
    ST_Transform(
        ST_Multi(
            ST_GeomFromGeoJSON('{geojson_str}'::JSON)
        ), 
    3857)
);
"""
    return query

def process_geojson_files():
    """Process all GeoJSON files and write SQL inserts to appropriate files."""
    for folder in os.listdir(ROOT_DIR):
        folder_path = os.path.join(ROOT_DIR, folder)
        if os.path.isdir(folder_path):
            entity_type = folder
            sql_filename = f"{entity_type}.sql"

            with open(sql_filename, "w", encoding="utf-8") as sql_file:
                for file in os.listdir(folder_path):
                    if file.endswith(".geojson"):
                        try:
                            entity_id = int(os.path.splitext(file)[0])
                            file_path = os.path.join(folder_path, file)
                            with open(file_path, "r", encoding="utf-8") as f:
                                geometry = json.load(f)
                                query = get_insert_query(entity_id, entity_type, geometry)
                                sql_file.write(query + "\n")
                        except Exception as e:
                            print(f"Error processing {file}: {e}")

if __name__ == "__main__":
    process_geojson_files()
