package com.mybus17000.data

import com.google.android.gms.maps.model.PolylineOptions

data class RoutePolylineBus(
    val stops: List<String>,
    val polyline: PolylineOptions,
    val routeId: String
)

data class RouteSegmentBest(
    val polyline: PolylineOptions,
    val fromStop: String,
    val toStop: String,
    val routeId: String
)

data class RouteResultBest(
    val segments: List<RouteSegmentBest>,
    val transferStop: String? = null
)

fun findBestRoute(
    startStopId: String,
    endStopId: String,
    routes: Map<String, RoutePolylineBus>
): RouteResultBest? {
    // 🔹 1. Ligne directe
    for ((routeId, route) in routes) {
        if (route.stops.contains(startStopId) && route.stops.contains(endStopId)) {
            val segment = RouteSegmentBest(
                fromStop = startStopId,
                toStop = endStopId,
                routeId = routeId,
                polyline = route.polyline
            )
            return RouteResultBest(listOf(segment))
        }
    }

    // 🔹 2. Recherche avec une correspondance
    for ((routeId1, route1) in routes) {
        if (!route1.stops.contains(startStopId)) continue
        for ((routeId2, route2) in routes) {
            if (!route2.stops.contains(endStopId)) continue
            val transferStops = route1.stops.intersect(route2.stops.toSet())
            if (transferStops.isNotEmpty()) {
                val transfer = transferStops.first()
                val seg1 = RouteSegmentBest(
                    fromStop = startStopId,
                    toStop = transfer,
                    routeId = routeId1,
                    polyline = route1.polyline
                )
                val seg2 = RouteSegmentBest(
                    fromStop = transfer,
                    toStop = endStopId,
                    routeId = routeId2,
                    polyline = route2.polyline
                )
                return RouteResultBest(listOf(seg1, seg2), transferStop = transfer)
            }
        }
    }

    // ❌ Aucun itinéraire trouvé
    return null
}

