Expand and improve this script as much as possible. This is meant to be doing FTTH GPON fibre network designs, see if you can reach atleast a thousand lines of code: import osmnx as ox
import simplekml
import numpy as np
import tkinter as tk
from tkinter import messagebox, ttk
import logging
import json
import os

# Set up logging
logging.basicConfig(level=logging.INFO)

def load_user_preferences(filepath="user_preferences.json"):
    """Load user preferences from a JSON file."""
    if os.path.exists(filepath):
        with open(filepath, "r") as file:
            return json.load(file)
    return {}

def save_user_preferences(pref_dict, filepath="user_preferences.json"):
    """Save user preferences to a JSON file."""
    with open(filepath, "w") as file:
        json.dump(pref_dict, file, indent=4)

def retrieve_data(area_name):
    """Retrieve road and building data from OpenStreetMap for the specified area."""
    logging.info(f"Retrieving road networks and building data for {area_name}...")
    graph = ox.graph_from_place(area_name, network_type='drive')
    buildings = ox.features_from_place(area_name, tags={'building': True})
    logging.info("Data retrieval complete!")
    return graph, buildings

def design_network(graph, buildings, fiber_ratio):
    """Design the GPON FTTH network by determining OLT and splitter placements."""
    logging.info("Designing GPON FTTH network...")
    
    OLT_location = list(graph.nodes())[0]
    olt_coords = (graph.nodes[OLT_location]['y'], graph.nodes[OLT_location]['x'])
    customer_locations = [building.geometry for _, building in buildings.iterrows()]

    splitters = []
    for i in range(0, len(customer_locations), int(fiber_ratio.split(':')[1])):
        splitter_location = customer_locations[i]
        splitters.append(splitter_location)

    logging.info(f"OLT placed at {olt_coords}, {len(customer_locations)} customer locations identified.")
    return olt_coords, splitters, customer_locations

def calculate_distances(olt_location, customer_locations):
    """Calculate distances from OLT to each customer location."""
    distances = []
    for customer in customer_locations:
        customer_coords = customer.centroid.coords[0]
        distance = np.linalg.norm(np.array(olt_location) - np.array(customer_coords))
        distances.append((customer_coords, distance))
    return distances

def generate_kml(olt_location, splitters, customer_locations, distances, deployment_option):
    """Generate a KML file representing the GPON network."""
    logging.info("Generating KML file...")
    kml = simplekml.Kml()

    kml.newpoint(name="OLT", coords=[(olt_location[1], olt_location[0])])
    
    for i, splitter in enumerate(splitters):
        splitter_coords = splitter.centroid.coords[0]
        line = kml.newlinestring(name="Fiber Line", coords=[(olt_location[1], olt_location[0]), 
                                                               (splitter_coords[0], splitter_coords[1])])
        line.style.linestyle.color = simplekml.Color.red
        line.style.linestyle.width = 2
        line.description = f"Feeder line from OLT to Splitter {i + 1}, Fiber Count: 144F"
        
        manhole_point = kml.newpoint(name="Manhole", coords=[(splitter_coords[0], splitter_coords[1])])
        manhole_point.description = "Manhole for fiber splice enclosure."

    for customer_coords, distance in distances:
        color = simplekml.Color.blue if deployment_option == 'underground' else simplekml.Color.green
        line_name = "Underground Drop Fiber Line" if deployment_option == 'underground' else "Overhead Drop Fiber Line"

        line = kml.newlinestring(name=line_name, coords=[(olt_location[1], olt_location[0]), 
                                                          (customer_coords[0], customer_coords[1])])
        line.style.linestyle.color = color
        line.style.linestyle.width = 2
        line.description = f"Drop fiber line to customer, Distance: {distance:.2f} meters, Fiber Count: 2F"

        boundary_box = kml.newpolygon(name="Customer Boundary Box", outerboundaryis=list(customer_coords))
        boundary_box.style.polystyle.color = simplekml.Color.changealphaint(100, simplekml.Color.blue)

    kml_file_name = "GPON_Network_Design.kml"
    kml.save(kml_file_name)
    
    logging.info(f"KML file created successfully: {kml_file_name}")
    messagebox.showinfo("Success", f"KML file created successfully: {kml_file_name}")


def run_network_design():
    """Run the entire network design process and gather user inputs from the GUI."""
    area_name = area_name_entry.get()
    fiber_ratio = fiber_ratio_combobox.get()
    deployment_option = deployment_option_combobox.get()

    try:
        graph, buildings = retrieve_data(area_name)
        olt_location, splitters, customer_locations = design_network(graph, buildings, fiber_ratio)
        distances = calculate_distances(olt_location, customer_locations)
        generate_kml(olt_location, splitters, customer_locations, distances, deployment_option)
    except Exception as e:
        messagebox.showerror("Error", str(e))


# GUI Setup
root = tk.Tk()
root.title("GPON FTTH Network Design Tool")

# Create labels and input fields
tk.Label(root, text="Area Name:").grid(row=0, column=0)
area_name_entry = tk.Entry(root, width=30)
area_name_entry.grid(row=0, column=1)

tk.Label(root, text="Fiber Ratio:").grid(row=1, column=0)
fiber_ratio_combobox = ttk.Combobox(root, values=["1:4", "1:8", "1:16"], state="readonly")
fiber_ratio_combobox.grid(row=1, column=1)
fiber_ratio_combobox.current(0)  # Set default selection

tk.Label(root, text="Deployment Option:").grid(row=2, column=0)
deployment_option_combobox = ttk.Combobox(root, values=["underground", "overhead"], state="readonly")
deployment_option_combobox.grid(row=2, column=1)
deployment_option_combobox.current(0)  # Set default selection

# Button to run network design
run_button = tk.Button(root, text="Run Network Design", command=run_network_design)
run_button.grid(row=3, column=0, columnspan=2)

# Start the GUI main loop
root.mainloop()