Fix this: import os
import pandas as pd
import geopandas as gpd
import osmnx as ox
from fastkml import kml
import zipfile
import logging

# Set up logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# Convert KMZ to KML
def kmz_to_kml(kmz_file, kml_file):
    if not os.path.exists(kmz_file):
        logging.error(f"KMZ file not found: {kmz_file}")
        return
    try:
        with zipfile.ZipFile(kmz_file, 'r') as kmz:
            kml_files = [name for name in kmz.namelist() if name.endswith('.kml')]
            if not kml_files:
                raise FileNotFoundError("No KML file found in KMZ archive.")
            kmz.extract(kml_files[0])
            if os.path.exists(kml_file):
                os.remove(kml_file)
            os.rename(kml_files[0], kml_file)
        logging.info("KMZ converted to KML successfully.")
    except FileNotFoundError as fnfe:
        logging.error(f"File not found in KMZ: {fnfe}")
    except zipfile.BadZipFile as bzf:
        logging.error(f"Bad zip file: {bzf}")
    except PermissionError as pe:
        logging.error(f"Permission error: {pe}")
    except Exception as e:
        logging.error(f"Error in kmz_to_kml: {e}")

# Parse KML to GeoDataFrame
def parse_kml_to_gdf(kml_file):
    if not os.path.exists(kml_file):
        logging.error(f"KML file not found: {kml_file}")
        return None

    try:
        k = kml.KML()
        with open(kml_file, 'rb') as f:
            k.from_string(f.read())

        features = list(k.features())
        placemarks = [placemark for feature in features for placemark in feature.features()]

        if not placemarks:
            logging.warning("No placemarks found in KML file.")
            return None

        names = []
        geometries = []

        for placemark in placemarks:
            if hasattr(placemark, 'geometry'):
                names.append(placemark.name)
                geometries.append(placemark.geometry)

        if not names or not geometries:
            logging.warning("No valid placemarks found with geometry.")

        gdf = gpd.GeoDataFrame({'name': names, 'geometry': geometries}, crs="EPSG:4326")

        if gdf.empty:
            logging.warning("GeoDataFrame is empty after parsing KML file.")
        else:
            logging.info(f"Parsed {len(gdf)} destinations from KML file.")

        return gdf
    except pd.errors.EmptyDataError as ede:
        logging.error(f"Empty data error in parse_kml_to_gdf: {ede}")
    except Exception as e:
        logging.error(f"Error in parse_kml_to_gdf: {e}")
    return None

# Load the road network
def load_road_network(shp_file):
    if not os.path.exists(shp_file):
        logging.error(f"Shapefile not found: {shp_file}")
        return None

    try:
        gdf = gpd.read_file(shp_file)
        if 'geometry' not in gdf.columns:
            logging.error("Shapefile missing 'geometry' column.")
            return None

        gdf_nodes = gdf[gdf.geometry.type == 'Point'].copy()
        gdf_edges = gdf[gdf.geometry.type != 'Point'].copy()

        if gdf_nodes.empty:
            logging.warning("No point geometries found in shapefile.")

        # Ensure 'x' and 'y' columns are present in the nodes dataframe
        if 'x' not in gdf_nodes.columns or 'y' not in gdf_nodes.columns:
            gdf_nodes[['x', 'y']] = gdf_nodes.geometry.apply(lambda geom: pd.Series(geom.coords[0]) if geom else pd.Series([None, None]))

        if gdf_edges.empty:
            logging.warning("No edge geometries found in shapefile.")

        # Create graph
        G = ox.graph_from_gdfs(gdf_nodes[['x', 'y']], gdf_edges)
        logging.info("Road network loaded successfully.")
        return G
    except pd.errors.EmptyDataError as ede:
        logging.error(f"Empty data error in load_road_network: {ede}")
    except MemoryError as me:
        logging.error(f"Memory error in load_road_network: {me}")
    except Exception as e:
        logging.error(f"Error in load_road_network: {e}")
    return None

# Main execution
def main():
    kmz_file = 'input.kmz'
    kml_file = 'destinations.kml'
    shp_file = 'area.shp'

    try:
        # Convert KMZ to KML
        kmz_to_kml(kmz_file, kml_file)

        # Parse KML to GeoDataFrame
        gdf_destinations = parse_kml_to_gdf(kml_file)
        if gdf_destinations is None:
            raise ValueError("Failed to parse KML file into GeoDataFrame.")

        # Load road network
        G = load_road_network(shp_file)
        if G is None:
            raise ValueError("Failed to load road network.")

        # Do further processing with gdf_destinations and G
        logging.info("Road network and destinations processed successfully.")
    except ValueError as ve:
        logging.error(f"ValueError in main: {ve}")
    except MemoryError as me:
        logging.error(f"MemoryError in main: {me}")
    except Exception as e:
        logging.error(f"Unexpected error in main: {e}")

if __name__ == '__main__':
    main()