import json
import polyline
from django.conf import settings
from pxy_dashboard.apps.models import OptScenario

def get_dispatch_data_for(subdivision):
    """
    Load the last OptScenario, decode its VROOM JSON for this subdivision,
    and return a list of routes, each with 'route_id', 'coords', and 'steps'.
    """
    scenario = OptScenario.objects.last()
    if not scenario or not scenario.dispatch_json:
        return None

    # load & slice
    with open(scenario.dispatch_json.path, encoding='utf-8') as f:
        raw = json.load(f)
    raw_subdiv = raw.get(subdivision)
    if not raw_subdiv:
        return None

    dispatch_data = []
    for route in raw_subdiv.get('routes', []):
        vehicle = route.get('vehicle')
        # decode polyline geometry → [ [lon, lat], … ]
        coords = []
        if route.get('geometry'):
            pts = polyline.decode(route['geometry'])
            coords = [[lng, lat] for lat, lng in pts]

        # build steps
        steps = []
        for step in route.get('steps', []):
            lon, lat = step['location']
            popup = (
                f"{step.get('type','job').title()}<br>"
                f"ID: {step.get('id','–')}<br>"
                f"Load: {step.get('load',[0])[0]} kg"
            )
            steps.append({
                'position': [lon, lat],
                'popup': popup,
                'step_type': step.get('type','job'),
            })

        dispatch_data.append({
            'route_id': str(vehicle),
            'coords': coords,
            'steps': steps,
        })

    return dispatch_data
