'''
🧭 How to run the full setup

Create your route file, Save your latitude/longitude list as route.txt.

Run the simulator     -    python traffic_simulator.py


This will continuously update traffic_sim.geojson in the same folder.
Start a simple local web server (so Leaflet can fetch the file)
python -m http.server 8000
Then open:
👉 http://localhost:8000/traffic_viewer.html

You’ll see the route and up to 10 red markers moving smoothly around the map — continuously looping, each at a unique speed and start position.


'''
from geojson import Point, Feature, FeatureCollection, dump
import json
import time
import math
import random

# ------------------------------------------------------------
# Helper functions
# ------------------------------------------------------------

def read_route_from_file(filename):
    """Read lat,lon pairs from a text file (comma or space separated)."""
    route = []
    with open(filename, 'r') as f:
        for line in f:
            parts = line.strip().replace(',', ' ').split()
            if len(parts) >= 2:
                lat, lon = map(float, parts[:2])
                route.append((lat, lon))
    return route

def interpolate_points(p1, p2, steps):
    """Generate intermediate points between p1 and p2."""
    lat1, lon1 = p1
    lat2, lon2 = p2
    points = []
    for i in range(1, steps):
        t = i / steps
        lat = round((lat1 + (lat2 - lat1) * t),6) #rounding added by mick
        lon = round((lon1 + (lon2 - lon1) * t),6) #rounding added by mick       
        points.append((lat, lon))
    return points

def generate_full_path(route, interpolation_steps=10):
    """Create a smooth path with interpolated points."""
    full_path = []
    for i in range(len(route)):
        p1 = route[i]
        p2 = route[(i + 1) % len(route)]  # loop back to start
        full_path.append(p1)
        full_path.extend(interpolate_points(p1, p2, interpolation_steps))
    return full_path

def create_geojson(route, markers):
    """Create a GeoJSON structure with route and marker points."""
    # features = [         ###  route line not needed                ###
        # {
            # "type": "Feature",
            # "properties": {"type": "route"},
            # "geometry": {
                # "type": "LineString",
                # "coordinates": [[lon, lat] for lat, lon in route]
            # }
        # }
    # ]

    features = []

    for i, marker in enumerate(markers):
        text_title = "FG" + str(i)
        point = Point((marker[1], marker[0]))
       # features.append(Feature(geometry=point, properties={"color": "red", "title": callsn, "heading" : "123", "speed": curspeed}))
        features.append(Feature(geometry=point,properties={"title": text_title, "make": "vehicle"}))
       # features.append({"type": "Feature","geometry": {"type": "Point","coordinates": [marker[1], marker[0]]},"properties": {"title": i, "make": "vehicle"}}) # original

    return {"type": "FeatureCollection", "features": features}

def write_geojson(filename, geojson_data):
    with open(filename, 'w') as f:
        #json.dump(geojson_data, f, indent=2)  # original but includes LF
        dump(geojson_data, f)

# ------------------------------------------------------------
# Main simulation logic
# ------------------------------------------------------------

def simulate_traffic(route_file, output_file, num_vehicles=10, interpolation_steps=20):
    route = read_route_from_file(route_file)
    if len(route) < 2:
        print("Need at least 2 route points.")
        return

    path = generate_full_path(route, interpolation_steps)

    # Create random start positions and speeds
    vehicle_positions = [random.randint(0, len(path)-1) for _ in range(num_vehicles)]
    vehicle_speeds = [random.randint(1, 5) for _ in range(num_vehicles)]  # step increments

    print("Simulating traffic... Press Ctrl+C to stop.")

    while True:
        # Update positions
        for i in range(num_vehicles):
            vehicle_positions[i] = (vehicle_positions[i] + vehicle_speeds[i]) % len(path)

        # Get current marker coordinates
        markers = [path[pos] for pos in vehicle_positions]

        # Build GeoJSON
        geojson_data = create_geojson(path, markers)
        write_geojson(output_file, geojson_data)

        time.sleep(1)  # update every half second

# ------------------------------------------------------------
# Run
# ------------------------------------------------------------
if __name__ == "__main__":
    simulate_traffic("/var/www/wildgate.org/public_html/route.txt", "/var/www/wildgate.org/public_html/traffic.json", num_vehicles=10, interpolation_steps=20)
